I made a function to make a circular animation. Function takes radius:float as input. I have done this in a ViewController Class and it is working fine for that view controller. But now i want to use this animation on multiple view controllers and don't want to write the same code on every single view controller. So i want to know how can i make this function in a separate file in such a way that i only need to call the function with the radius and it will do the work. Or can you tell me the best practice to do that. Thanks in advance.
//
I dont want to do it in myViewController i just want to create a new class only for circular animation. and also dont want to import that class want to do like this-
import UIKit
class CircularProgressView {
private let shapeLayer = CAShapeLayer()
public func createProgressView(radius:CGFloat,forView:UIView) {
let center = forView.center
let circularPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: -CGFloat.pi/2, endAngle: 2*CGFloat.pi, clockwise: true)
let trackLayer = CAShapeLayer()
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor.lightGray.cgColor
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineWidth = 10
forView.layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 10
shapeLayer.lineCap = .round
shapeLayer.strokeEnd = 0
forView.layer.addSublayer(shapeLayer)
forView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
}
@objc private func handleTap() {
print("hello s")
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
basicAnimation.toValue = 1
basicAnimation.duration = 2
basicAnimation.fillMode = .forwards
basicAnimation.isRemovedOnCompletion = false
shapeLayer.add(basicAnimation, forKey: "basic")
}
}
and use this like- import UIKit
class ViewController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
CircularProgressView().createProgressView(radius: 50, forView: view)
}
}
but in this code guesture recogniser is not working.
You can simply create a UIViewController
extension
and add a method animate(with:)
in it with the relevant code,
extension UIViewController {
func animate(with radius: Float) {
//add your code here..
}
}
The method animate(with:)
is now available to all UIViewController
subclasses. So, you can simply call it like so
class VC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.animate(with: 10.0)
}
}
There is no need to create any parent class
in this case.