ios - 如何在单个文件中定义的多个 View Controller 中使用属性?

标签 ios swift storyboard uikit

我制作了一个制作圆形动画的功能。函数以 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/

相关文章:

ios - 当我们在 iOS 设备上安装应用程序时第一次访问 iOS 应用程序中的联系人时如何显示警报 View ?

ios - 适用于 iphone 和 ipad 的应用程序的启动图像

ios - XIB 中 View 的正确宽度?

ios - 无法为 Storyboard设置覆盖的库类

ios - 在 Storyboard 应用程序上,如何在应用程序期间从 AppDelegate 呈现 View Controller :didFinishLaunchingWithOptions:?

swift - 如何制作自定义圆形 UIImageView 子类?

ios - Swift *.stringsdict 返回波兰值的错误键

ios - 当 Core Data 对象更新时更新 UIViewController

iOS:具有动态单元格高度的 UITableViewCell 内的 UITableView

Swift Codable 在嵌套字典上崩溃