簡體   English   中英

Swift-在UIViewController內部擴展UIView

[英]Swift - Extension UIView inside of UIViewController

我的意圖是在用戶嘗試使用按鈕而不填充所有字段的情況下使屏幕抖動。

出現以下錯誤:

類型'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")
    }
}

您需要從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")
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM