ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

 iOS - How to make Animations of a UIImageView in Swift

Updated on October 12, 2017

Here you’ll learn how to move a UIImageView using UIViewAnimation property and other nice stuff in Swift.

We’ve setup a demo project that looks like this:

Let’s start from declaring our UIImageView into ViewController.swift file by ctrl+drag from the image (we’ve called it “myImage”) into the .swift file:

    @IBOutlet weak var myImage: UIImageView!

Now let’s see what code is needed for the Move Image blue button (of course we’ve declared it into our .swift file again by ctrl+drag from the button to the code):

@IBAction func moveImage(sender: AnyObject) {
    UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: {
        self.myImage.frame.origin.y = 160
    }, completion: { (finished: Bool) in
        println("Animation Ended!")

We will explain you what happens in the code above line by line:

  1. IBAction for our Move Image button
  2. Statement to call UIViewAnimations function, here we set its duration in seconds, the delay for when the animation should start (still in seconds) and the options, which means how our animation should behave like. You may try some test by deleting “.CurveLinear” and type one of the following options: .CurveEaseInOut, .CurveEaseIn and .CurveEaseOut
  3. Here we set our UIImageView new vertical origin (position on the screen). Please note that the 160 value we have set in our sample project means that our image will stop its animation when its top-left corner point will get to 160 pixels from the top of the screen (which is 0). Also, when writing code into a block statement like UIViewAnimation in Swift, you need to put self. before your view’s name or else XCode will not recognize it.
  4. This is the Completion block, we can add some other methods that our code will fire as soon as the animation ends
  5. Print a message on the XCode’s Console that says the animation has ended.

Run the app and tap on Move Image blue button, you’ll see our missile icon moving down to 160 pixels. Pretty cool, right?

All right, let’s now check what Set Alpha = 0 red button does:

@IBAction func setAlpha0(sender: AnyObject) {
    UIView.animateWithDuration(0.5, delay: 0.5, options: UIViewAnimationOptions.CurveLinear, animations: {
        self.myImage.alpha = 0.1
    }, completion: { (finished: Bool) in
        println("Alpha has changed into \(self.myImage.alpha)")

Line by line what happens above:

  1. IBAction for our button
  2. UIViewAnimation statement, as explained above, please note that here we’ve set 0.5 as delay, so our animation will start 0.5 seconds after tapping the button
  3. Here we set the opacity of our image to 0.1. Alpha values go from 0.0 to 1.0
  4. Completion block, again
  5. Print a message that says the alpha value of our image in the XCode’s Console

Run the app again and tap on Set Alpha = 0 red button, you’ll see that our missile will fade slowly in 0.5 seconds, after 0.5 seconds.

Head over now to the Rotate 90° Clockwise green button, here’s its code:

@IBAction func rotate90degrees(sender: AnyObject) {
    UIView.animateWithDuration(0.8, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: {
        self.myImage.transform = CGAffineTransformMakeRotation( CGFloat(M_PI_2) );
    }, completion: { (finished: Bool) in
        println("Image has rotate 90° clockwise")

This time we’ll explain only line 3 (you know the rest already). Here we’ve used CGAffineTransformMakeRotation function to rotate our missile of 90°. Please note that in Swift you have to declare a float value with a CGFloat expression: CGFloat(MY_FLOAT_NUMBER). Also, the common variable for 90° in XCode is M_PI_2, you cannot replace it with a value like 90.0, it won’t work.

Run the code again and tap on the green button, you’ll get a final result like this:

Ok, we’re almost done, now we wanted to implement a last button to reset ourmissile image so bring it back to its original position, alpha and rotation status. Here’s the code for the black Reset Image button:

@IBAction func resetImage(sender: AnyObject) {
    UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: {
        self.myImage.frame.origin.y = 20
        self.myImage.alpha = 1
    }, completion: { (finished: Bool) in
        self.myImage.transform = CGAffineTransformMakeRotation(0);

Line by line what happens in the code above:

  1. IBAction for our black button
  2. UIViewAnimation statement
  3. Set the origin Y of our image back to 20px from the top of the screen
  4. Set opacity back to 1
  5. Completion block
  6. Here we’ve put the rotation function back to 0, which means that the image will return to its original rotation state. Only in this case we can set a numeric value.

Run again the app, play with the colored buttons and then tap the black one, our image will go back to its original state.

Thanks for reading, don't forget to check out our other tutorials!

© 2015 cubycode


Submit a Comment

No comments yet.


This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

Show Details
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)