user2722667
user2722667

Reputation: 8661

swift animateWithDuration breaks when I try to edit text label outside code block

In my app I have two sort buttons that looks like a custom segmented control.

The VC inits with Button1 selected. If you then press on Button2 a UIView will animate from Button1 to Button2 - this is effect to show what button is selected

My code looks like this:

@IBAction func BtnOneDidTouch(sender: AnyObject) {
        myLabel.text = "Button 1"
        UIView.animateWithDuration(0.7,
            delay: 0,
            usingSpringWithDamping: 0.7,
            initialSpringVelocity: 0.5,
            options: nil,
            animations: {
                self.underLine.center = CGPointMake(self.btnOne.center.x, self.btnOne.center.y + 16)
            }, completion: nil
        )
    }


    @IBAction func BtnTwoDidTouch(sender: AnyObject) {
        myLabel.text = "Button 2"
        UIView.animateWithDuration(0.7,
            delay: 0,
            usingSpringWithDamping: 0.7,
            initialSpringVelocity: 0.5,
            options: nil,
            animations: {
                self.underLine.center = CGPointMake(self.btnTwo.center.x, self.btnTwo.center.y + 16)
            }, completion: nil
        )
    }

underLine is the view that is being animated.

If I comment out

myLabel.text = "Button 1"

and myLabel.text = "Button 2"

from the functions it will work. But If I leave them, it does not work.

It fails by: If you click on Btn2 the view will slide then jump back again and only the text label will be changed.

What I want to is to have the view slide and stay and change the label as well.

Upvotes: 0

Views: 726

Answers (1)

Rory McKinnel
Rory McKinnel

Reputation: 8014

The problem is likely down to constraints. The view you are animating probably has constraints you gave it or which have been given to it by xcode.

When you set the text, it is causing layout to fire which is warping the view back to the initial auto layout location.

Try setting the animated views translatesAutoresizingMaskIntoConstraints property to NO.

Alternatively, give the view a leading and top constraint, CTRL drag these to create IBOutlets, then in code change the constraint constants and animate the constraint change.

For details on how to animate constraints see: How do I animate constraint changes?

Upvotes: 1

Related Questions