How can I repeat a function and change a variable each time? - ios

I am trying to repeat the function createCircle() multiple times and each time I want to change the button.center value, how can I do this and still keep the animation for each circle? Currently when I try and repeat the variable by copying and pasting the function createCircle() with different positioning, my animation handleTap() will not work on the other circles.
import UIKit
class SecondViewController: UIViewController {
let shapeLayer = CAShapeLayer()
let percentageLabel: UILabel = {
let label = UILabel()
label.text = ""
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 28)
label.textColor = UIColor(red: 0.59, green: 0.42, blue: 0.23, alpha: 1.00)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
createCircle()
}
func createCircle() {
let trackLayer = CAShapeLayer()
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.clipsToBounds = true
button.center = view.center
button.addTarget(self, action: #selector(handleTap), for: .touchUpInside)
view.addSubview(button)
let circularPath = UIBezierPath(arcCenter: .zero, radius: 50, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor(red: 0.82, green: 0.69, blue: 0.52, alpha: 1.00).cgColor
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineWidth = 10
trackLayer.position = view.center
view.layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor(red: 0.59, green: 0.42, blue: 0.23, alpha: 1.00).cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 10
shapeLayer.lineCap = CAShapeLayerLineCap.round
shapeLayer.position = view.center
shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi / 2, 0, 0, 1)
view.addSubview(percentageLabel)
percentageLabel.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
percentageLabel.center = view.center
}
var done = 0
var toDo = 0
#objc func handleTap() {
toDo = 5
if done < toDo {
done += 1
} else {
done -= toDo
}
let percentage = CGFloat(done) / CGFloat(toDo)
percentageLabel.text = "\(Int(percentage * 100))%"
DispatchQueue.main.async {
self.shapeLayer.strokeEnd = percentage
}
view.layer.addSublayer(shapeLayer)
}
}

Related

How can I use the same button and action multiple times, but affect the layer instead of the view

I am trying to use the same button in each createCircle() function, but when I press a button and it runs the handleTap() function, it only applies to the most recently added circle. I would like to use the same button but when I click on an individual button it should run the animation on the one I pressed.
import UIKit
class SecondViewController: UIViewController {
let shapeLayer = CAShapeLayer()
let percentageLabel: UILabel = {
let label = UILabel()
label.text = ""
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 28)
label.textColor = UIColor(red: 0.59, green: 0.42, blue: 0.23, alpha: 1.00)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
_ = createCircle(positionX: 100, positionY: 200)
_ = createCircle(positionX: 100, positionY: 375)
_ = createCircle(positionX: 100, positionY: 550)
_ = createCircle(positionX: 100, positionY: 725)
_ = createCircle(positionX: 300, positionY: 200)
_ = createCircle(positionX: 300, positionY: 375)
_ = createCircle(positionX: 300, positionY: 550)
_ = createCircle(positionX: 300, positionY: 725)
}
//MARK: - Create Circle
func createCircle(positionX: Int, positionY: Int) -> (CGPoint) {
let trackLayer = CAShapeLayer()
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.clipsToBounds = true
button.center = view.center
button.addTarget(self, action: #selector(handleTap), for: .touchUpInside)
view.addSubview(button)
let circularPath = UIBezierPath(arcCenter: .zero, radius: 50, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor(red: 0.82, green: 0.69, blue: 0.52, alpha: 1.00).cgColor
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineWidth = 10
trackLayer.position = CGPoint(x: positionX, y: positionY)
view.layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor(red: 0.59, green: 0.42, blue: 0.23, alpha: 1.00).cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 10
shapeLayer.lineCap = CAShapeLayerLineCap.round
shapeLayer.position = CGPoint(x: positionX, y: positionY)
shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi / 2, 0, 0, 1)
view.addSubview(percentageLabel)
percentageLabel.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
percentageLabel.center = CGPoint(x: positionX, y: positionY)
return CGPoint(x: positionX, y: positionY)
}
//MARK: - Tap function
var done = 0
var toDo = 0
#objc func handleTap(sender: UIButton) {
toDo = 5
if done < toDo {
done += 1
} else {
done -= toDo
}
let percentage = CGFloat(done) / CGFloat(toDo)
percentageLabel.text = "\(Int(percentage * 100))%"
DispatchQueue.main.async {
self.shapeLayer.strokeEnd = percentage
}
view.layer.addSublayer(shapeLayer)
}
}
This is a picture of what happens when I run my code. When I click on any of the pictured buttons, instead of running the progress bar animation on whichever button I pressed, it only runs it on the button that was added last to the view controller.
Instead of using createCircle() in your view controller, make a new file for it and initialize the function like this inside.
import UIKit
class Button: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
createCircle()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let percentageLabel: UILabel = {
let label = UILabel()
label.text = ""
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 28)
label.textColor = UIColor(red: 0.59, green: 0.42, blue: 0.23, alpha: 1.00)
return label
}()
let shapeLayer = CAShapeLayer()
func createCircle() {
let trackLayer = CAShapeLayer()
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.clipsToBounds = true
button.center = center
button.addTarget(self, action: #selector(handleTap), for: .touchUpInside)
addSubview(button)
let circularPath = UIBezierPath(arcCenter: .zero, radius: 50, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor(red: 0.82, green: 0.69, blue: 0.52, alpha: 1.00).cgColor
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineWidth = 10
trackLayer.position = center
layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor(red: 0.59, green: 0.42, blue: 0.23, alpha: 1.00).cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 10
shapeLayer.lineCap = CAShapeLayerLineCap.round
shapeLayer.position = center
shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi / 2, 0, 0, 1)
addSubview(percentageLabel)
percentageLabel.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
// percentageLabel.center = CGPoint(x: positionX, y: positionY)
// return CGPoint(x: positionX, y: positionY)
}
var done = 0
var toDo = 0
#objc func handleTap(sender: UIButton) {
toDo = 5
if done < toDo {
done += 1
} else {
done -= toDo
}
let percentage = CGFloat(done) / CGFloat(toDo)
percentageLabel.text = "\(Int(percentage * 100))%"
DispatchQueue.main.async {
self.shapeLayer.strokeEnd = percentage
}
layer.addSublayer(shapeLayer)
}
}
You can remove the code from your secondViewController that has to do with your button and call the circle function inside of your viewDidLoad(). The problem was that your animation was affecting your view (not an individual circle), by creating a class for your circle button, you can call it in your secondViewController and it will affect only the circle in which the button was pressed.

How to Change uitextfield leftView image tintColor on editing

I'm trying to achieve UITextField editing or not editing style like this:
But the trickiest part for me is How to change that left image tint color. I have achieved this so far:
My code:
UITextField
lazy var email: UITextField = {
let name = UITextField()
name.layer.cornerRadius = 17.5
name.layer.borderColor = UIColor(red: 0.55, green: 0.61, blue: 0.69, alpha: 0.5).cgColor
name.layer.borderWidth = 1.5
name.placeholder = "Email"
name.font = UIFont.systemFont(ofSize: 15)
name.textColor = UIColor(red: 0.55, green: 0.61, blue: 0.69, alpha: 1)
name.backgroundColor = .clear
name.leftViewMode = UITextFieldViewMode.always
name.delegate = self
name.translatesAutoresizingMaskIntoConstraints = false
return name
}()
leftImage func:
func addLeftImageTo(txtField: UITextField, andImage img: UIImage) {
let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 42.75, height: 40))
let centerX: CGFloat = (leftView.frame.midX) - (img.size.width / 2)
let centerY: CGFloat = (leftView.frame.midY) - (img.size.height / 2)
let leftImageView = UIImageView(frame: CGRect(x: centerX + 2 , y: centerY - 1, width: img.size.width, height: img.size.height))
leftImageView.contentMode = .scaleAspectFit
leftImageView.image = img
leftView.addSubview(leftImageView)
txtField.leftView = leftView
txtField.leftViewMode = .always
}
Adding leftImages:
let emailLeftImg = UIImage(named: "ic_txt_field_email")
addLeftImageTo(txtField: email, andImage: emailLeftImg!)
let passwordLeftImg = UIImage(named: "ic_txt_field_password")
addLeftImageTo(txtField: password, andImage: passwordLeftImg!)
editingBegains and Ending:
func textFieldDidBeginEditing(_ textField: UITextField) {
self.setTextBorder(textField: textField, color: UIColor.white, borderColor: UIColor.white, isSelected: true)
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.setTextBorder(textField: textField, color: UIColor.clear, borderColor: UIColor(red: 0.55, green: 0.61, blue: 0.69, alpha: 0.5), isSelected: false)
}
func setTextBorder(textField: UITextField, color: UIColor, borderColor: UIColor, isSelected: Bool) {
textField.backgroundColor = color
textField.layer.borderColor = borderColor.cgColor
textField.tintColor = UIColor(red: 1.0, green: 0.2, blue: 0.33, alpha: 1)
textField.layer.masksToBounds = false
if isSelected == true {
textField.layer.shadowRadius = 3.0
textField.layer.shadowColor = UIColor.black.cgColor
textField.layer.shadowOffset = CGSize(width: 0, height: 2)
textField.layer.shadowOpacity = 0.125
} else {
textField.layer.shadowRadius = 0
textField.layer.shadowColor = UIColor.clear.cgColor
textField.layer.shadowOffset = CGSize(width: 0, height: 0)
textField.layer.shadowOpacity = 0
}
}
I had tried adding this code to change Image color but it didn't work.
var picTintColor: Bool = false
In LeftImage func:
if picTintColor == true {
leftImageView.image = img.withRenderingMode(.alwaysTemplate)
leftImageView.tintColor = .blue
} else {
leftImageView.image = img
}
And in editingBegains and Ending func:
if isSelected == true {
picTintColor = true
} else {
picTintColor = false
}
I'm a complete noob in IOS programming so thanks for your patience and sorry for my bad english. Thanks!
According the code ,it actually can not pass isSelected signal to the leftImageView,maybe leftImageView get in laster is not the earlier ,or the signal not pass successly.
I suggest that a easy way to do, just in editingBegains and Ending: to do what you want change the imageview,like this:
func textFieldDidBeginEditing(_ textField: UITextField) {
let emailLeftImg = UIImage(named: "ic_txt_field_email")
addLeftImageTo(txtField: email, andImage: emailLeftImg!)
}
func addLeftImageTo(txtField: UITextField, andImage img: UIImage) {
let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 42.75, height: 40))
let centerX: CGFloat = (leftView.frame.midX) - (img.size.width / 2)
let centerY: CGFloat = (leftView.frame.midY) - (img.size.height / 2)
let leftImageView = UIImageView(frame: CGRect(x: centerX + 2 , y: centerY - 1, width: img.size.width, height: img.size.height))
leftImageView.contentMode = .scaleAspectFit
if picTintColor == true {
leftImageView.image = img.withRenderingMode(.alwaysTemplate)
leftImageView.tintColor = .blue
} else {
leftImageView.image = img
}
leftView.addSubview(leftImageView)
txtField.leftView = leftView
txtField.leftViewMode = .always
}
and in end delgate method ,just do that ,you can try this way to test.Hope to help you.

Centering CAShapeLayer within UIView Swift

I'm having trouble centering CAShapeLayer within a UIView. I've search and most solutions are from pre 2015 in Obj C or haven't been solved.
Attached is what the image looks like. When I inspect it, its inside the red view, but idk why its not centering. I've tried resizing it but still doesn't work.
let progressView: UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
//MARK: - ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(progressView)
progressView.anchor(top: nil, left: nil, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 200, height: 200)
progressView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
progressView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
setupCircleLayers()
}
var shapeLayer: CAShapeLayer!
private func setupCircleLayers() {
let trackLayer = createCircleShapeLayer(strokeColor: UIColor.rgb(red: 56, green: 25, blue: 49, alpha: 1), fillColor: #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1))
progressView.layer.addSublayer(trackLayer)
}
private func createCircleShapeLayer(strokeColor: UIColor, fillColor: UIColor) -> CAShapeLayer {
let centerpoint = CGPoint(x: progressView.frame.width / 2, y: progressView.frame.height / 2)
let circularPath = UIBezierPath(arcCenter: centerpoint, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
let layer = CAShapeLayer()
layer.path = circularPath.cgPath
layer.fillColor = fillColor.cgColor
layer.lineCap = kCALineCapRound
layer.position = progressView.center
return layer
}
As #ukim says, your problem is that you are trying to determine the position of your layer, based on views and their size before these are finite.
When you are in viewDidLoad you don't know the size and final position of your views yet. You can add the progressView alright but you can not be sure that its size or position are correct until viewDidLayoutSubviews (documented here).
So, if I move your call to setupCircleLayers to viewDidLayoutSubviews and I change the centerpoint to CGPoint.zero and alter the calculation of your layer.position to this:
layer.position = CGPoint(x: progressView.frame.size.width / 2, y: progressView.frame.size.height / 2)
Then I see this:
Which I hope is more what you were aiming for.
Here is the complete listing (note that I had to change some of your methods as I didn't have access to anchor or UIColor.rgb for instance but you can probably work your way around that :))
import UIKit
class ViewController: UIViewController {
var shapeLayer: CAShapeLayer!
let progressView: UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(progressView)
progressView.translatesAutoresizingMaskIntoConstraints = false
progressView.heightAnchor.constraint(equalToConstant: 200).isActive = true
progressView.widthAnchor.constraint(equalToConstant: 200).isActive = true
progressView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
progressView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if shouldAddSublayer {
setupCircleLayers()
}
}
private func setupCircleLayers() {
let trackLayer = createCircleShapeLayer(strokeColor: UIColor.init(red: 56/255, green: 25/255, blue: 49/255, alpha: 1), fillColor: #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1))
progressView.layer.addSublayer(trackLayer)
}
private var shouldAddSublayer: Bool {
/*
check if:
1. we have any sublayers at all, if we don't then its safe to add a new, so return true
2. if there are sublayers, see if "our" layer is there, if it is not, return true
*/
guard let sublayers = progressView.layer.sublayers else { return true }
return sublayers.filter({ $0.name == "myLayer"}).count == 0
}
private func createCircleShapeLayer(strokeColor: UIColor, fillColor: UIColor) -> CAShapeLayer {
let centerpoint = CGPoint.zero
let circularPath = UIBezierPath(arcCenter: centerpoint, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
let layer = CAShapeLayer()
layer.path = circularPath.cgPath
layer.fillColor = fillColor.cgColor
layer.lineCap = kCALineCapRound
layer.position = CGPoint(x: progressView.frame.size.width / 2, y: progressView.frame.size.height / 2)
layer.name = "myLayer"
return layer
}
}
Hope that helps.
Caveat
When you do the above, that also means that every time viewDidLayoutSubviews is called, you are adding a new layer. To circumvent that, you can use the name property of a layer
layer.name = "myLayer"
and then check if you have already added your layer. Something like this should work:
private var shouldAddSublayer: Bool {
/*
check if:
1. we have any sublayers at all, if we don't then its safe to add a new, so return true
2. if there are sublayers, see if "our" layer is there, if it is not, return true
*/
guard let sublayers = progressView.layer.sublayers else { return true }
return sublayers.filter({ $0.name == "myLayer"}).count == 0
}
Which you then use here:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if shouldAddSublayer {
setupCircleLayers()
}
}
I've updated the listing.
You are calling setupCircleLayers()in viewDidLoad(). At the time, progressView.frame has not been calculated from the constraints yet.
Try
let centerpoint = CGPoint(x: 100, y: 100)
instead of calculating the value from progressView.frame
You can try this in your playground:
import UIKit
import PlaygroundSupport
class MyVC: UIViewController {
let progressView: UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
var layer: CAShapeLayer?
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(progressView)
progressView.translatesAutoresizingMaskIntoConstraints = false
progressView.backgroundColor = .red
progressView.widthAnchor.constraint(equalToConstant: 200).isActive = true
progressView.heightAnchor.constraint(equalToConstant: 200).isActive = true
progressView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
progressView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
setupCircleLayers()
}
var shapeLayer: CAShapeLayer!
private func setupCircleLayers() {
let trackLayer = createCircleShapeLayer(strokeColor: .red, fillColor: #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1))
progressView.layer.addSublayer(trackLayer)
}
private func createCircleShapeLayer(strokeColor: UIColor, fillColor: UIColor) -> CAShapeLayer {
let centerpoint = CGPoint(x: 100, y: 100)
let circularPath = UIBezierPath(arcCenter: centerpoint, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
let layer = CAShapeLayer()
layer.path = circularPath.cgPath
layer.fillColor = fillColor.cgColor
layer.lineCap = kCALineCapRound
return layer
}
}
let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0))
let vc = MyVC()
PlaygroundPage.current.liveView = vc.view

My indicator is blank [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I use a custom indicator but when i call the subclass indicator in my viewdidload my view controller is blank but when i run it in a playground i can see it in the side window. Here is the code of the indicator. Theres no error but my indicator is not showing. Thats my problem. I would appreciate it if someone could tell me why.
import UIKit
class MaterialLoadingIndicator: UIView {
let MinStrokeLength: CGFloat = 0.05
let MaxStrokeLength: CGFloat = 0.7
let circleShapeLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
initShapeLayer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initShapeLayer() {
circleShapeLayer.actions = ["strokeEnd" : NSNull(),
"strokeStart" : NSNull(),
"transform" : NSNull(),
"strokeColor" : NSNull()]
circleShapeLayer.backgroundColor = UIColor.clear.cgColor
circleShapeLayer.strokeColor = UIColor.blue.cgColor
circleShapeLayer.fillColor = UIColor.clear.cgColor
circleShapeLayer.lineWidth = 5
circleShapeLayer.lineCap = kCALineCapRound
circleShapeLayer.strokeStart = 0
circleShapeLayer.strokeEnd = MinStrokeLength
let center = CGPoint(x: bounds.width*0.5, y: bounds.height*0.5)
circleShapeLayer.frame = bounds
circleShapeLayer.path = UIBezierPath(arcCenter: center,
radius: center.x,
startAngle: 0,
endAngle: CGFloat(M_PI*2),
clockwise: true).cgPath
layer.addSublayer(circleShapeLayer)
}
func startAnimating() {
if layer.animation(forKey: "rotation") == nil {
startColorAnimation()
startStrokeAnimation()
startRotatingAnimation()
}
}
private func startColorAnimation() {
let color = CAKeyframeAnimation(keyPath: "strokeColor")
color.duration = 10.0
color.values = [UIColor(hex: 0x4285F4, alpha: 1.0).cgColor,
UIColor(hex: 0xDE3E35, alpha: 1.0).cgColor,
UIColor(hex: 0xF7C223, alpha: 1.0).cgColor,
UIColor(hex: 0x1B9A59, alpha: 1.0).cgColor,
UIColor(hex: 0x4285F4, alpha: 1.0).cgColor]
color.calculationMode = kCAAnimationPaced
color.repeatCount = Float.infinity
circleShapeLayer.add(color, forKey: "color")
}
private func startRotatingAnimation() {
let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.toValue = M_PI*2
rotation.duration = 2.2
rotation.isCumulative = true
rotation.isAdditive = true
rotation.repeatCount = Float.infinity
layer.add(rotation, forKey: "rotation")
}
private func startStrokeAnimation() {
let easeInOutSineTimingFunc = CAMediaTimingFunction(controlPoints: 0.39, 0.575, 0.565, 1.0)
let progress: CGFloat = MaxStrokeLength
let endFromValue: CGFloat = circleShapeLayer.strokeEnd
let endToValue: CGFloat = endFromValue + progress
let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
strokeEnd.fromValue = endFromValue
strokeEnd.toValue = endToValue
strokeEnd.duration = 0.5
strokeEnd.fillMode = kCAFillModeForwards
strokeEnd.timingFunction = easeInOutSineTimingFunc
strokeEnd.beginTime = 0.1
strokeEnd.isRemovedOnCompletion = false
let startFromValue: CGFloat = circleShapeLayer.strokeStart
let startToValue: CGFloat = fabs(endToValue - MinStrokeLength)
let strokeStart = CABasicAnimation(keyPath: "strokeStart")
strokeStart.fromValue = startFromValue
strokeStart.toValue = startToValue
strokeStart.duration = 0.4
strokeStart.fillMode = kCAFillModeForwards
strokeStart.timingFunction = easeInOutSineTimingFunc
strokeStart.beginTime = strokeEnd.beginTime + strokeEnd.duration + 0.2
strokeStart.isRemovedOnCompletion = false
let pathAnim = CAAnimationGroup()
pathAnim.animations = [strokeEnd, strokeStart]
pathAnim.duration = strokeStart.beginTime + strokeStart.duration
pathAnim.fillMode = kCAFillModeForwards
pathAnim.isRemovedOnCompletion = false
CATransaction.begin()
CATransaction.setCompletionBlock {
if self.circleShapeLayer.animation(forKey: "stroke") != nil {
self.circleShapeLayer.transform = CATransform3DRotate(self.circleShapeLayer.transform, CGFloat(M_PI*2) * progress, 0, 0, 1)
self.circleShapeLayer.removeAnimation(forKey: "stroke")
self.startStrokeAnimation()
}
}
circleShapeLayer.add(pathAnim, forKey: "stroke")
CATransaction.commit()
}
func stopAnimating() {
circleShapeLayer.removeAllAnimations()
layer.removeAllAnimations()
circleShapeLayer.transform = CATransform3DIdentity
layer.transform = CATransform3DIdentity
}
}
extension UIColor {
convenience init(hex: UInt, alpha: CGFloat) {
self.init(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hex & 0x0000FF) / 255.0,
alpha: CGFloat(alpha)
)
}
}
And here is the code of my view controller in the viewdidload
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
let indicator = MaterialLoadingIndicator(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
indicator.center = CGPoint(x: 320*0.5, y: 568*0.5)
view.addSubview(indicator)
indicator.startAnimating()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The view holding the indicator is just floating around, feeling lost, feeling unhappy for not belonging to, not being added to someone. :)
EDIT :
Okay John, now that we are stuck, let us add the indicator to someone.
override func viewDidLoad() {
super.viewDidLoad()
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
let indicator = MaterialLoadingIndicator(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
indicator.center = CGPoint(x: 320*0.5, y: 568*0.5)
view.addSubview(indicator)
indicator.startAnimating()
self.view.addSubview(view) // John, this is what was missing
}

After CAReplicatorLayer animation in a `vc`'s `subview`, switch `vc` comes a strange issue

CAReplicator did not keep the state after the switch vc:
Dots of CAReplicator did not keep its scale after the vc switch back.
As you see, the circle animation is created by CAReplicator.
after the main vc switch to another vc, then switch back, the Circle's dots become very small. witch is set in the initial.
My code is below:
In the main vc:
func initUI() {
let lml_frame = CGRect.init(x: 0, y: 64, width: self.view.bounds.size.width, height: 400)
lml_digtal_view = LMLDigitalDazzleAnimationView.init(frame: lml_frame)
self.view.addSubview(lml_digtal_view!)
}
In the LMLDigitalDazzleAnimationView:
import Foundation
import UIKit
class LMLDigitalDazzleAnimationView: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
var initFrame = CGRect.init(x: 0, y: 0, width: 320, height: 480)
var fromColor = UIColor.init(red: 240/255.0, green: 77.0/255.0, blue: 48.0/255.0, alpha: 1.0).cgColor
var toColor = UIColor.init(red: 220.0/255.0, green: 28.0/255.0, blue: 44.0/255.0, alpha: 1.0).cgColor
var money:Float? = 1200.25 {
didSet {
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initFrame = frame
initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initUI(){
let gradul_layer = CAGradientLayer.init()
gradul_layer.frame = CGRect.init(x: 0, y: 0, width: initFrame.width, height: initFrame.height)
gradul_layer.colors = [
fromColor,
toColor
]
gradul_layer.startPoint = CGPoint.init(x: 0.5, y: 0.3)
gradul_layer.endPoint = CGPoint.init(x: 0.5, y: 0.7)
layer.addSublayer(gradul_layer)
let wave_view0 = KHWaveView.init(frame: CGRect.init(x: 0, y: initFrame.height - 80, width: initFrame.width, height: 80))
//wave_view.backgroundColor = UIColor.white
wave_view0.waveColor = UIColor.init(red: 1, green: 1, blue: 1, alpha: 0.5)
wave_view0.waveSpeed = 1.3
wave_view0.waveTime = 0
wave_view0.wave()
self.addSubview(wave_view0)
let wave_view = KHWaveView.init(frame: CGRect.init(x: 0, y: initFrame.height - 80, width: initFrame.width, height: 80))
//wave_view.backgroundColor = UIColor.white
wave_view.waveColor = UIColor.white
wave_view.waveSpeed = 1.0
wave_view.waveTime = 0
wave_view.wave()
self.addSubview(wave_view)
animateCircle()
animateDigitalIcrease(money: money!)
}
func animateCircle() -> Void {
let r = CAReplicatorLayer()
r.bounds = CGRect(x:0.0, y:0.0, width:260.0, height:260.0)
r.cornerRadius = 10.0
r.backgroundColor = UIColor.clear.cgColor
r.position = CGPoint.init(x: self.bounds.width / 2.0, y: 160)
self.layer.addSublayer(r)
let dot = CALayer()
dot.bounds = CGRect(x:0.0, y :0.0, width:6.0, height:6.0)
dot.position = CGPoint(x:100.0, y:10.0)
dot.backgroundColor = UIColor(white:1, alpha:1.0).cgColor
dot.cornerRadius = 3.0
r.addSublayer(dot)
let nrDots: Int = 32
r.instanceCount = nrDots
let angle = CGFloat(2*M_PI) / CGFloat(nrDots)
r.instanceTransform = CATransform3DMakeRotation(angle, 0.1, 0.1, 1.0)
let duration:CFTimeInterval = 1.5
let shrink = CABasicAnimation(keyPath: "transform.scale")
shrink.fromValue = 1.0
shrink.toValue = 1.0 // 0.5
shrink.duration = duration
shrink.repeatCount = Float.infinity
dot.add(shrink, forKey: nil)
r.instanceDelay = duration/Double(nrDots)
dot.transform = CATransform3DMakeScale(0.1, 0.1, 0.1)
delay(delay: duration) {
let turn_key_path = "transform.rotation"
let turn_ani = CABasicAnimation.init(keyPath: turn_key_path)
turn_ani.isRemovedOnCompletion = false
turn_ani.fillMode = kCAFillModeForwards
turn_ani.toValue = M_PI*2
turn_ani.duration = 2.0
turn_ani.repeatCount = 2
r.add(turn_ani, forKey: turn_key_path)
}
}
func delay(delay:Double, closure:#escaping ()->()){
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
func animateDigitalIcrease(money :Float){
let frame = CGRect.init(x: 0, y: 0, width: 120, height: 80)
let counterLabel = LMLDigitalIncreaseLabel.init(frame: frame, andDuration: 2.0, andFromValue: 0, andToValue: money)
counterLabel?.center = CGPoint.init(x: self.bounds.size.width / 2.0, y: 130)
self.addSubview(counterLabel!)
counterLabel?.start()
delay(delay: 5.0) {
counterLabel?.stop()
self.animateFadeShowSmallMoney()
}
}
func animateFadeShowSmallMoney(){
let border_view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 30))
border_view.layer.cornerRadius = 15
border_view.layer.masksToBounds = true
border_view.layer.borderWidth = 1
border_view.backgroundColor = UIColor.clear
border_view.layer.borderColor = UIColor.white.cgColor
let small_money_frame = CGRect.init(x: 0, y: 0, width: 80, height: 30)
let small_money = UILabel.init(frame: small_money_frame)
small_money.center = border_view.center
small_money.adjustsFontSizeToFitWidth = true
small_money.textAlignment = NSTextAlignment.center
small_money.text = "mo:" + String(format:"%.2f", money!)
small_money.textColor = UIColor.white
border_view.addSubview(small_money)
border_view.alpha = 0.0
self.addSubview(border_view)
border_view.center = CGPoint.init(x: self.bounds.size.width/2.0, y: 220)
UIView.animate(withDuration: 1.0) {
border_view.alpha = 1.0
}
}
}
My code is not good, you can advice me how to encapsulate a animation class better.
After many attention, I solve my issue:
delay(delay: duration) {
let turn_key_path = "transform.rotation"
let turn_ani = CABasicAnimation.init(keyPath: turn_key_path)
turn_ani.isRemovedOnCompletion = false
turn_ani.fillMode = kCAFillModeForwards
turn_ani.toValue = M_PI*2
turn_ani.duration = 2.0
turn_ani.repeatCount = 2
r.add(turn_ani, forKey: turn_key_path)
dot.transform = CATransform3DMakeScale(1, 1, 1) // add this line solve my issue.
}

Resources