Tarang Hirani
Tarang Hirani

Reputation: 590

iOS Animation - View should be outside the superview

I have created a UIBezierPath object that I wish to move around the superview based on values received from the Accelerometer. I was trying to play around with UIView Animations and I am not quite sure I understand this code particularly well.

The code for the UIBezierPath object is below:

 override func drawRect(rect: CGRect) {
    let path = UIBezierPath(arcCenter: pathCenter, radius: pathRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true)
    UIColor.blueColor().setFill()
    UIColor.greenColor().setStroke()
    path.lineWidth = 2.0
    path.fill()
    path.stroke()
}

In the ViewController I perform the animation using the following code:

override func viewDidLoad() {
    super.viewDidLoad()
    UIView.animateWithDuration(0.5) { () -> Void in
        //self.ballView.center.x += self.view.frame.width
    }
    print(self.ballView.center.x)
    print(self.view.frame.width)
}

The confusion I am facing is about the dimensions of the ballView and superview (the ViewController's view)

This line self.ballView.center.x returns 187.5 and self.view.frame.width returns 375.0, so if I perform the commented line of code, self.ballView.center.x += self.view.frame.width shouldn't the ballView's center.x value be 555.75 and therefore outside the ViewControllers view. Instead the ballView is positioned at the center of the self.view. Please let me know what exactly is going on.

Upvotes: 1

Views: 429

Answers (1)

David Williames
David Williames

Reputation: 1109

Move the animation into a viewDidAppear method instead. Like so:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animateWithDuration(0.5) {
        self.ballView.center.x += self.view.frame.width
    }
}

Upvotes: 2

Related Questions