Animate objects in Swift?

11,150

Solution 1

Apples Core animation seen here https://developer.apple.com/library/Mac/DOCUMENTATION/Cocoa/Conceptual/CoreAnimation_guide/Introduction/Introduction.html its very fun. youtube it

Solution 2

I'm used to using [UIView animateWithDuration ...], but I found it a bit tricky switching the block syntax over to Swift at first. Here's a quick lazy code:

view.alpha = 0.0
UIView.animateWithDuration(0.25, animations: {
    view.alpha = 1.0
}, completion: {
    (value: Bool) in
    println(">>> Animation done.")
})

Solution 3

Or to animate the position appearing from the left of the screen:

// some variables for the UIView
let width = 200
let height = 100
let yPosition = 10

// create view and position it offscreen to the left    
let view = UIView()

// you could have also used the new more verbose Swift way of making a CGRect:
// CGRect(x: xValue, y: yValue, width: widthValue, height: heightValue)
view.frame = CGRectMake(-width, yPosition, width, height)
view.backgroundColor = UIColor.blueColor() // etc...

// animation position over 1.0 second duration
UIView.animateWithDuration(1.0, animations: {

    view.frame = CGRectMake(0, yPosition, width, height)
})

If you're completely new to the UIView animation APIs I wrote post that covers a bunch of animation options in swift here: http://mathewsanders.com/prototyping-iOS-iPhone-iPad-animations-in-swift/

Share:
11,150

Related videos on Youtube

Benr783
Author by

Benr783

Updated on June 04, 2022

Comments

  • Benr783
    Benr783 almost 2 years

    In swift, I am transitioning an object in to the view, and I need it to slide in, or fade in. How can I obtain this type of animation in my program?

    I have all my view elements made programmatically without IB (Interface Builder)

    Is there documentation I can look at for reference? I could not find any.

    • Kevin
      Kevin almost 10 years
      Same way as in Objective C.
    • Benr783
      Benr783 almost 10 years
      I can't find anything with the type of animation that I want. I just want maybe a simple slide in or fade in. Not an OpenGL game.
    • Cezary Wojcik
      Cezary Wojcik almost 10 years
      Look up UIView's animate methods. They work the same way in Swift as they did in Obj-C.
    • Abhi Beckert
      Abhi Beckert almost 10 years
      For slide or fade animations you want a CABasicAnimation or CAKeyframeAnimation, where you set the x/y position or the opacity via the animation. See documentation or other questions showing how to do it in Objective-C, there is plenty of it. If you get stuck, update this question with what you tried to do and a description of what isn't working.
  • Legolas
    Legolas over 8 years
    can you pls tell me how to animate continously..??
  • LordParsley
    LordParsley over 8 years
    Perhaps try something like stackoverflow.com/questions/28644335/…
  • uplearned.com
    uplearned.com about 6 years
    Link is broken hence -1