我制作了一个制作圆形动画的功能。函数以 radius:float 作为输入。我已经在 ViewController 类中完成了此操作,并且该 View Controller 工作正常。但是现在我想在多个 View Controller 上使用这个动画,并且不想在每个 View Controller 上编写相同的代码。所以我想知道如何在一个单独的文件中创建这个函数,这样我只需要用半径调用函数就可以了。或者你能告诉我这样做的最佳做法吗?
提前致谢。
//
我不想在 myViewController 中这样做,我只想为循环动画创建一个新类。并且也不想导入想要这样做的那个类-
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")
}
}
并使用这个像 -
导入 UIKit
class ViewController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
CircularProgressView().createProgressView(radius: 50, forView: view)
}
}
但在此代码中,访客识别器无法正常工作。
最佳答案
您可以简单地创建一个 UIViewController
extension
并添加一个方法animate(with:)
里面有相关的代码,
extension UIViewController {
func animate(with radius: Float) {
//add your code here..
}
}
方法
animate(with:)
现已对所有人开放UIViewController
子类。所以,你可以简单地这样称呼它class VC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.animate(with: 10.0)
}
}
无需创建任何父
class
在这种情况下。
关于ios - 如何在单个文件中定义的多个 View Controller 中使用属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59768676/