【问题标题】:How to call function from custom UIView class?如何从自定义 UIView 类调用函数?
【发布时间】:2018-06-06 06:38:57
【问题描述】:

我的第一个视图控制器中有 UIView。我已使用以下代码将该 UIView 类设置为自定义进度视图。

class ProgressView: UIView {
    let trackLayer = CAShapeLayer()
    let shapeLayer = CAShapeLayer()

    static let instance = ProgressView()

    override func awakeFromNib() {
        super.awakeFromNib()
        let center = CGPoint.init(x: frame.width / 2, y: frame.height / 2)
        let circularPath = UIBezierPath(arcCenter: center, radius: 30, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)

        trackLayer.path = circularPath.cgPath
        trackLayer.strokeColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
        trackLayer.lineWidth = 3
        trackLayer.fillColor = #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
        trackLayer.lineCap = kCALineCapRound
        self.layer.addSublayer(trackLayer)
        shapeLayer.path = circularPath.cgPath
        shapeLayer.strokeColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
        shapeLayer.lineWidth = 3
        shapeLayer.fillColor = #colorLiteral(red: 0.3794638515, green: 0.5145698786, blue: 0.9605538249, alpha: 1)
        shapeLayer.lineCap = kCALineCapRound
        shapeLayer.strokeEnd = 0
        self.layer.addSublayer(shapeLayer)
    }
}

自定义 UIView 类中还有一个函数,用于启动动画以使用以下代码填充圆圈

 func startProgress() {
    let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
    basicAnimation.toValue = 1
    basicAnimation.duration = 60        
    basicAnimation.fillMode = kCAFillModeForwards
    basicAnimation.isRemovedOnCompletion = false
    shapeLayer.add(basicAnimation, forKey: "soBasic")
}

我需要在我的 First View 控制器中调用 startProgress 函数。在 viewDidLoad 我调用了 ProgressView.instance.startProgress() 但它没有触发。如何从另一个类调用启动进度函数?

【问题讨论】:

  • 显示ProgressView.instance方法的定义,如果您的视图与xib相关联,还有另一种创建自定义UIView实例的方法。
  • 您是否将 ProgressView 添加到 FirstViewController 的视图中?
  • 首先,视图单例是个坏主意,因为一个 UIView 实例将只有一个 superView
  • @TheTiger 我没有创建 xib,它是我的视图控制器中的一个简单的 uiview,我将它的类设置为进度视图。
  • @AtalayAsa 你把它和IBOutlet 联系起来了吗?

标签: ios swift uiview cashapelayer


【解决方案1】:

ProgressView你需要创建一个初始化或者你可以使用默认的。

class ProgressView: UIView {

    //you can set any additional properties in it.

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 } 

如何使用

在您想要使用的视图控制器中...

let pgView = ProgressView() //or any other initialise if you have created
.
.
.
pgView.startProgress()

【讨论】:

  • 我很高兴 +1,@Atalay 不要创建 UIView 单例
  • 感谢您的评论,但它给了我一个错误 'super.init' 不能在初始化程序之外调用,并且关键字 'init' 不能在这里用作标识符我该如何解决? @MahendraGP
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多