限制UITableView到其父视图的边缘,无故事板

问题描述:

我有一个UITableView,我在viewDidLoad实例化,并希望限制到我的视图的边缘。限制UITableView到其父视图的边缘,无故事板

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]; 

这样做会导致系统崩溃/错误

2017年8月24日11:52:25.530554-0400 objtest [61964:48549108] *** 终止应用程序由于未捕获的异常 ' NSInvalidArgumentException',原因:'NSLayoutConstraint为 ; layer =; contentOffset:{0,0}; contentSize:{0,0}; adjustedContentInset:{0,0,0,0}>:乘数为0或零的第二个 项目与第一个属性的位置一起创建 位置等于常数的非法约束。位置 属性必须成对指定。'

我怎样才能使用NSLayoutConstraint(或更好的iOS内置)正确对齐?

+0

从类文档中指定的初始值设定项开始('initWithFrame:style:')。 –

对于这些约束,您希望“乘数”为1而不是0。