Fayza Nawaz
Fayza Nawaz

Reputation: 2316

Updating Constraints programmatically iOS

I need to update a constraint programmatically in my project to adjust a view's height accordingly (based on different subviews). I've made outlet of the constraint in my controller but facing an issue.

when I try to update this for the first time (in viewDidLoad or viewWillAppear method), it's not updated. and if i update it afterwards (because of some rotation etc), then it is done correctly. Kindly tell me why this is happening and what is the right way/place to do this? (As i feel that the constraint is updated somewhere again after my updation in viewWillAppear/DidLoad).

I tried view.layoutIfNeeded as well but it didn't help. I guess it has something to do with viewDidLoad and other viewController delegate methods

P.S. I'm also using size classes in my project but I think it has nothing to do with that as it's working in some cases.

Upvotes: 2

Views: 2345

Answers (1)

SwiftArchitect
SwiftArchitect

Reputation: 48524

Updating constraints may not work in viewWillAppear. It will, however, work in viewDidAppear.

There are other places you may overwrite, such as: (using static BOOL shouldRefreshView = NO; for the first time)

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if(shouldRefreshView) {
        shouldRefreshView = NO;
        [self.view layoutIfNeeded];
    }
}

Upvotes: 3

Related Questions