Swift - UIViewController内部的扩展UIView

问题描述 投票:0回答:1

我的意图是每当用户尝试使用按钮而没有填写所有字段时,屏幕就会动摇。

出现以下错误:

“AddViewController”类型的值没有成员'shake'

AddViewController属于类UIViewController,但更改扩展类也不起作用。

... else {
      self.shake()
        }
extension UIView {
    func shake() {
        let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
        animation.duration = 0.6
        animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
        layer.add(animation, forKey: "shake")
    }
}
ios swift xcode
1个回答
2
投票

您需要从vc的视图中调用它,因为扩展名适用于UIView

self.view.shake()

使用

self.shakeView() // directly inside the vc

extension UIViewController {
   func shakeView() {
    // .....
    // here use the view
     view.layer.add(animation, forKey: "shake")
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.