Rafael
Rafael

Reputation: 388

How to prevent AutoLayout from resetting view frames?

I have a view with AutoLayout and it works nicely with different screen sizes. There's one element on the screen though that moves around depending on user actions. Whenever I navigate down to a different screen then back to this view, this element gets reset to its original position.

I understand why this happens but how can I prevent it? I do want it to be setup correctly initially but not after the first time.

Upvotes: 0

Views: 1938

Answers (2)

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

The only solution I found is, Implement viewDidLayoutSubviews

It will invoke the layoutSubviews method just after the view is loaded..

- (void)viewDidLayoutSubviews
{
    @try
    {
         // Adjusting controls.
    }
    @catch (NSException *exception)
    {
        NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
    }
}

Upvotes: 3

iain
iain

Reputation: 5683

If you're using Autolayout you should never use setFrame/setBounds because as you've seen Autolayout ignores them and rewrites them when it updates.

The solution is to change the constraints. A constraint has a parameter called constant which is the only thing you can change on a constraint after it has been created. You can also add/remove extra constraints when you need to move NSViews around.

There is a video from WWDC 2012 that had a very good example of how to move views with AutoLayout.

Upvotes: 1

Related Questions