Search code examples
iosobjective-cuiviewcommitanimationsbeginanimations

Move a UIView with start point


I have this code below who move my UIView to left:

- (void)viewDidLoad {
    [super viewDidLoad];

    [UIView beginAnimations:nil context:NULL];

        [UIView setAnimationDuration:4];

        int xOriginal = 91;

        CGRect rect = imagem.frame;

        int x = rect.origin.x;
        int y = rect.origin.y;
        int w = rect.size.width;
        int h = rect.size.height;

        if(x == xOriginal){

            imagem.frame = CGRectMake(x+100, y, w, h);
        }else{

            imagem.frame = CGRectMake(x-100, y, w, h);
        }

        [UIView commitAnimations];

}

My coordinate of my view is x = 91 (Center of the superView), When I start my app my UIView start left and go to center, instead of center and go to right, Why this is happening?

How to make my UIView start in center (x=91) and go to right (91+100), instead of left to center?


Solution

  • Autolayout and frame animations are not good friends. Try to animate constraints instead of directly the frame.

    You can create outlets of your constraints, and set the constant property of the constraint in your code to move your views.
    You also call -[view layoutIfNeeded] to refresh your constraints while in an animation block.

    Else you can remove all of your view constraints and animate its frame fearlessly.