Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move a label and animate the change using Auto Layout?

I'm trying to move a UILabel to the left and animate the movement. The UILabel is created from a storyboard, and has the following constraints:

enter image description here

But if I try to make the trailing space constant equal to say, 150 instead of 20 to move it to the left, it bounces to the left weirdly for a second then comes back to the middle. So I lowered the priority of the left leading constraint to 900, but the same thing still happened.

So I tried:

self.textToReadLabel.transform = CGAffineTransformMakeTranslation(-500.0, 0.0);

Which moves it, but if I use an animation with it it slides off screen, slides back on and then rests in the place it should... after all those theatrics.

How exactly would I achieve this?

Entirety of what happens when I tap the button to move the label:

        self.textHorizontalPlacementConstraint.constant = 150.0;
        self.textHorizontalPlacementConstraint2.constant = -110.0;
        [UIView animateWithDuration:1.0 animations:^{
            [self.view layoutIfNeeded];
        }];

        CATransition *animation = [CATransition animation];
        animation.duration = 0.5;
        animation.type = kCATransitionFade;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [self.textToReadLabel.layer addAnimation:animation forKey:@"changeTextTransition"];

        // Change the text
        self.textToReadLabel.text = @"text";
    }

Video of what it looks like:

http://cl.ly/3l2E401N3Q3h

like image 839
Doug Smith Avatar asked Nov 12 '22 00:11

Doug Smith


1 Answers

You can set outlets of your constraints in the Interface Builder and then when you want to animate the change you modify your code as below:

    [UIView animateWithDuration:2.0 animations:^{
        //Change your constraints from code.
    }];

For Eg: if I have a leftSpacing Constraint I can directly change it as below:

    [UIView animateWithDuration:2.0 animations:^{
        //Change your constraints from code.
        self.leftSpacing.constant = self.leftSpacing.constant+20;
        [self.view layoutIfNeeded];
    }];

The above code will animate your view from left to right by 20 points.

UPDATE:

Have you tried adding multiple constraints: like spacing value should be less than or equal to say:200 but greater than or equal to 20. I think that may help.

like image 112
Geekoder Avatar answered Nov 15 '22 05:11

Geekoder