Zack Shapiro
Zack Shapiro

Reputation: 6998

Constraining UITableView to the edges of its parent view without storyboards

I have a UITableView that I'm instantiating in viewDidLoad and want to constrain to the edges of my view.

UITableView *tableView = [[UITableView alloc] init];
[tableView setBackgroundColor:[UIColor blackColor]];
tableView.delegate = self;
tableView.dataSource = self;
tableView.rowHeight = 44;

[self.view addSubview:tableView];

[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:0 constant:0].active = YES;

[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:0 constant:0].active = YES;

[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:0 constant:0].active = YES;

[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:0 constant:0].active = YES;

[self.view layoutIfNeeded];

Doing this causes a crash/error

2017-08-24 11:52:25.530554-0400 objtest[61964:48549108] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSLayoutConstraint for ; layer = ; contentOffset: {0, 0}; contentSize: {0, 0}; adjustedContentInset: {0, 0, 0, 0}>: A multiplier of 0 or a nil second item together with a location for the first attribute creates an illegal constraint of a location equal to a constant. Location attributes must be specified in pairs.'

How can I get this properly aligned using NSLayoutConstraint (or something better built into iOS)?

Upvotes: 1

Views: 115

Answers (1)

Erik Westwig
Erik Westwig

Reputation: 744

You want the "multiplier" to be 1 not 0 for those constraints.

Upvotes: 3

Related Questions