user11204114
user11204114

Reputation:

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

Upvotes: 0

Views: 660

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

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

Upvotes: 2

Related Questions