Rohan Agarwal
Rohan Agarwal

Reputation: 2187

iOS View Hierarchy for setting up Auto Layout Constraint

What is the closest ancestor to self.navigationController.navigationBar and a subview of self.view in a view controller so I can add the constraint to that ancestor?

self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
[self.searchBar setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:self.searchBar];

NSLayoutConstraint* cn = [NSLayoutConstraint constraintWithItem:self.searchBar  
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual 
toItem:self.navigationController.navigationBar attribute:NSLayoutAttributeBottom 
multiplier:1.0 constant:0];

I tried doing

[self.view addConstraint:cn];
[self.navigationController.view addConstraint:cn];

but both times I get the error, "Does the constraint reference something from outside the subtree of the view? That's illegal."

Can someone explain the view hierarchy of a view controller in relation to the navigationController?

Thanks!

Upvotes: 0

Views: 2324

Answers (1)

rdelmar
rdelmar

Reputation: 104082

The view tree looks like this:

enter image description here

So, navigationController.view is the closest ancestor of the navigation bar and your view. I'm not sure why that didn't work. Where did you put that code?

Upvotes: 1

Related Questions