简体   繁体   中英

Swift - Extension UIView inside of UIViewController

My intention is whenever the user tries to use the button without having all the fields filled in, to have the screen shake.

Following error appears:

Value of type 'AddViewController' has no member 'shake'

AddViewController is of class UIViewController , but changing the extensions class won't work either.

... 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")
    }
}

You need to call it from the vc's view as the extension is for UIView

self.view.shake()

To use

self.shakeView() // directly inside the vc

Do

extension UIViewController {
   func shakeView() {
    // .....
    // here use the view
     view.layer.add(animation, forKey: "shake")
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM