[source code] iOS Development with Swift Tutorial - 28, 29, & 30 - UIKit Dynamics

+3 Bucky Roberts · February 8, 2015

import UIKit

class ViewController: UIViewController {

    //Create two shapes
    var greenSquare: UIView?
    var redSquare: UIView?
    var animator: UIDynamicAnimator?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Create the shapes
        var dimen = CGRectMake(25, 25, 60, 60)
        greenSquare = UIView(frame: dimen)
        greenSquare?.backgroundColor = UIColor.greenColor()
        
        dimen = CGRectMake(130, 25, 90, 90)
        redSquare = UIView(frame: dimen)
        redSquare?.backgroundColor = UIColor.redColor()
        
        //Add them to the screen
        self.view.addSubview(greenSquare!)
        self.view.addSubview(redSquare!)
        
        //Initialize the animator
        animator = UIDynamicAnimator(referenceView: self.view)
        
        //Gravity
        let gravity = UIGravityBehavior(items: [greenSquare!, redSquare!] )
        let direction = CGVectorMake(0.0, 1.0)
        gravity.gravityDirection = direction
        
        //Collision
        let boundries = UICollisionBehavior(items: [greenSquare!, redSquare!] )
        boundries.translatesReferenceBoundsIntoBoundary = true
        
        //Elasticity
        let bounce = UIDynamicItemBehavior(items: [greenSquare!, redSquare!] )
        bounce.elasticity = 0.5
        
        animator?.addBehavior(bounce)
        animator?.addBehavior(boundries)
        animator?.addBehavior(gravity)
    }

}

Post a Reply

Replies

Oldest  Newest  Rating
0 Adam Streamer · February 13, 2015
thanks for code!
  • 1

iOS Development / Swift

107,349 followers
About

This forum is for questions, comments, and general discussion about iOS Development and Swift.

Links
Moderators
Bucky Roberts Administrator