Pablo Blanco
Pablo Blanco

Reputation: 79

How to move UIViews in a controller using autolayout

I'm updating an app to iOS7/8, and applying autolayout features. In my UIViewController I have a few UIViews whose position should be modified as a UIScrollView updates its contentOffset.

When I update the UIView's frame (old way), I get some glitches and errors because of the controller autolayout constraints (I am using VFL for setting constraints programatically, I don't have a storyboard).

So the question is: which is the right/best way to move UIViews in a controller that implements Autolayout? Maybe updating constraints? Should I use Core Animation to make any UIView move?

Thanks in advance!

Upvotes: 0

Views: 164

Answers (2)

marosoaie
marosoaie

Reputation: 2371

If you have the constraints set-up in the storyboard you can set an outlet for whatever constraint you need to update (just like you do for any view). Once you do that, you can update the constraint constant property as you need.

[self layoutIfNeeded];
topConstraint.constant += 200;
[UIView animateWithDuration:0.3 animations:^{
        [self layoutIfNeeded];
    }]; 

In the code above i am updating the topConstraint for a view and animating the changes. You need to call [self layoutIfNeeded]; once before the constraint is modified, and again in the animation block.

Upvotes: 3

Pablo A.
Pablo A.

Reputation: 2052

self.yourView.translatesAutoresizingMaskIntoConstraints = YES;

And then just change the frame:

CGRect rect = self.yourView.frame;
// move or change size
rect.origin.x = whatever...
self.yourView.frame = rect.

Upvotes: -1

Related Questions