简体   繁体   中英

UIkit Dynamics in swift

Trying to convert some objective c code to swift and struggling to achieve results.

animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
_gravity = [[UIGravityBehavior alloc] initWithItems:@[square]];

at to moment I have got

animator.referenceView = self.view

Doesn't work though. Can someone guide me in the right direction. Thanks in advance

Full Code

let square = UIView()

    square.frame = CGRectMake(100, 100, 100, 100)
    square.backgroundColor = UIColor.redColor()

  self.view.addSubview(square)

    var animator = UIDynamicAnimator()
    var gravity = UIGravityBehavior()



    animator.referenceView = self.view

    animator.addBehavior(gravity)

holex was on to it, but the key is that you have to store a reference to the animator, here's a working example:

class ViewController: UIViewController {

    var animator:UIDynamicAnimator?

    override func viewDidLoad() {
        super.viewDidLoad()

        let square = UIView()

        square.frame = CGRectMake(100, 100, 100, 100)
        square.backgroundColor = UIColor.redColor()

        self.view.addSubview(square)

        self.animator = UIDynamicAnimator(referenceView:self.view)
        var gravity = UIGravityBehavior(items: [square])

        animator!.addBehavior(gravity)

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM