pajevic
pajevic

Reputation: 4657

Adding subview to UITableView with autolayout doesn't set its frame

I am using the following code to add a overlay view to a view:

UIView *overlayView = [[UIView alloc] init];
overlayView.backgroundColor = [UIColor redColor];

[self.view addSubview:overlayView];

overlayView.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *views = NSDictionaryOfVariableBindings(overlayView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[overlayView]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[overlayView]|" options:0 metrics:nil views:views]];

If I place this code in the viewDidLoad method of a UIViewController it works fine. However, if I do the same in a UITableViewController the overlay view gets a zero frame.

I have inspected the view and I can se the constraints do get added correctly and they are active. But for som reason they seem to be ignored.

I don't get any error or warning.

What am I missing here?

PS: I know I can instantiate the overlay view with self.view.bounds as frame, and it works. However, I need to use autolayout.

Upvotes: 0

Views: 1836

Answers (1)

Protongun
Protongun

Reputation: 3260

Suspect it's because the UITableView is a UIScrollView and auto layout has a few caveats when working with views that establish their own bounds systems (such as the scroll view or table view).

The constraints set on the overlay view are such that it is constrained to the top, right, bottom, and left edges of the scroll view, and thus to the content area of the scroll view rather than the scroll view's frame.

See https://developer.apple.com/library/ios/technotes/tn2154/_index.html and Auto Layout Guide: Working with Scroll Views:

Constraints between the edges or margins of the scroll view and its content attach to the scroll view’s content area.

Instead of constraining overlay view to the content area, constrain it to the scroll view's frame instead. According to the above references, this can be done either by constraining overlay view's width/height to the scroll view, or by constraining the overlay view to a view outside of the scroll view.

Upvotes: 2

Related Questions