0
votes

I have two views, one visible (grey) and one hidden (red). The visible view is constraint to the superview top with a constant of 32, and the other constraint to the superview top with a constant of 16.

The top of the visible view is also constrained to the bottom of the hidden view, with a constant of 8. This constraint has a priority of 749, because it is initially unsatisfiable.

The idea is that the visible (grey) view should be 32 points below the superview normally, but when the hidden (red) view is made visible, the original (grey) view should be 8 points below the other view (red).

I'm achieving this by keeping a strong reference to the 32-point constraint, and making it active/inactive as I'm hiding/unhiding the view (red).

Here's a picture of my layout:

Screenshot

This works very well normally, but I've been trying to set constraint.active = NO and redView.hidden = NO in viewDidLoad, as I need the textfield to display an error if a certain condition has not been met. For some reason, this does not work. The red view is displayed as expected, but the second view (grey) does not move down as it should (it does not respect the 749 constraint, even if the main constraint is no longer active). Here's a picture of the result:

Not working initially

However, I made the code to inactivate the constraint and display the view run after a small delay (using dispatch_after();), and then it suddenly works as expected:

Works after delay

My question is: why doesn't the view respect the constraint and move down when it is run immediately from viewDidLoad? Why does it suddenly work after a small delay? Is this a decent solution of achieving my goal, given I can get it to work properly?

2

2 Answers

2
votes

call it in viewDidLayoutSubviews methode not in viewdidload. autolayout it take some time to load so call it in viewDidLayoutSubviews.

1
votes

While using autolayout - (void)viewDidLoad will return the frame which you gave in storyboard.

You have to use - (void)viewDidLayoutSubviews to update the frame according to constraints.

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    //Replace self.view by your view whose constraints need to update
    [self.view layoutIfNeeded];
}