swalkner
swalkner

Reputation: 17339

UITableView and AutoLayout - no table shown

I'm creating a UITableView in code and I'd like to set up the size with constraints - but no tableView is shown:

_tableView = [[UITableView alloc] initWithFrame:CGRectZero];
_tableView.translatesAutoresizingMaskIntoConstraints = NO;
_tableView.autoresizingMask = UIViewAutoresizingNone;
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];

NSDictionary *views = @{ @"tableView": self.tableView};
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[tableView]-10-|" options:0 metrics:nil views:views]];
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[tableView]-10-|" options:0 metrics:nil views:views]];

[self.view removeConstraints:self.view.constraints];
[self.view addConstraints:constraints];

Only without constraints and if I use initWithFrame:self.view.bounds the table is shown... what am I missing?

EDIT: it doesn't help if I'm initializing the tableView with self.view.bounds

EDIT 2: Everything seems to be fine if I delete self.view.translatesAutoResizingMaskIntoConstraints = NO; which I also have in my viewDidLoad - why isn't that allowed?

Upvotes: 1

Views: 964

Answers (1)

jrturton
jrturton

Reputation: 119242

Everything seems to be fine if I delete self.view.translatesAutoResizingMaskIntoConstraints = NO; which I also have in my viewDidLoad - why isn't that allowed?

I'm glad you found the answer - here's an explanation for you.

For view controller views that are managed by the system, including but not limited to:

  • The root view controller of the window
  • A view controller pushed onto a navigation controller
  • One of the options in a tab bar controller

You don't want to turn on autolayout. The size and position of view is not up to the view controller to decide in these circumstances, and you don't know how the containing object is sizing your view. If it wants to use autolayout, it will turn off the autoresizing mask translation property itself.

The only time you'd make your view controller's view an autolayout view is if you were using it as a child view controller in another view controller, and you wanted to use constraints to size and position the child view controller's view. Even in that case you'd probably not set the property within the view controller, but let the parent do it.

You don't need to turn on autolayout for every view in your hierarchy. Autolayout views can live quite happily inside "legacy layout" views.

Upvotes: 2

Related Questions