Move a UIView with start point

1.2k views Asked by At

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?

4

There are 4 answers

5
Crazyrems On BEST ANSWER

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.

0
Monikanta On
[UIImageView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear  animations:^{
                imagem.frame=CGRectMake(imagem.frame.origin.x+100, imagem.frame.origin.y, imagem.frame.size.width, imagem.frame.size.height);

   } completion:^(BOOL finished) {
                //code for completion
                NSLog(@"Animation complete");
            }];
1
madhu On
Initially image.frame = CGRectMake(91,100,20,20);
So imageview starting point is 0

[UIView animateWithDuration:5.0
  animations:^{
    //Animation code goes here
   image.frame = CGRectMake(191,100,20,20); //Now imageview moves from 0 to 100
  } completion:^(BOOL finished) {
    //Code to run once the animation is completed goes here
}];
0
Duncan C On

As the other poster says, you can't animate a view's frame in XIBs/storyboards that use AutoLayout.

Instead you have to animate a constraint that's attached to the view.

What you do is to create a constraint (or multiple constraints) and connect it to an IBOutlet. Then, in your animation code, you calculate the changes to the constraint(s) and change the constant for the appropriate constraints.

For example, if you wanted to shift the vertical position of a view, set up a constraint that sets the vertical position of your view, and link it to an IBOutlet called viewConstraint. Then you'd use code like this:

[myView animateWithDuration: .25
  animations: ^
  {
    viewConstraint.constant -= shiftAmount;
    [self.view layoutIfNeeded];
  }
];