View on GitHub

Shake Images with Swift 3

Getting Started

After launching xcode and creating a new project with single view
application, go to File -> New -> File
This will present to you a new window with multiple file options, make sure the top bar is selecting iOS, then choose Swift File and click Next
name the file shakeableImageView then click create

Writing the shakabel extension

In Swift programing there is this idea of extensions and protocols. Extensions is implementing function that can be used to a certain type of class. For example, adding an extension to a class double to print as with two decimal places and a dollar sign. In this this site we will be adding an extension to an image view (UIImageView) so that it has the ability to be shaking whenever the user taps it. Go to the file shakeableImageView you just created and remove everything, except the top comment, and add the following

Linking an image from the storyboard

Now go to the storyboad and add an image to your viewController, then link the image to your ViewController.swift. Save this image and drag and drop it to your project. Add it as an image in your story board
In the storyboard click press ctl and drag to your file as shown in the following picture. Name the image bulldogImg

Tap gesture recognizer

Now your the image is linked your code file, but how would your code know if the image was pressed or not. In swift every class that has the name view in it confirms to all view protocols, and one of those protocols is isUserInteractionEnabled, which makes it user insteractive. However this will not allow us to do a certain thing when the user is pressed, what we need is to know whent the image was pressed and what to do when it is pressed. So another protocol that the View classes anser to is addGestureRecognizer
we can use this so that whenever the user tap we call a function and shake the image.
Hence, add the following to your ViewController in the viewDidLoad() function. When you add this function it will give you an error in defineing tap because we haven't implemented the imageTapped function

Tap gesture handler

Now that we added the tap gesture to the image we need to handel it. and what we need to do is to shake the image everytime the user tap it so first we need to declare a the imageTapped function

Now using our protocol, since the image is UIImageView write the following