我有一个要在UITableView中实例化的viewDidLoad,并且想约束到视图的边缘。

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-08-24 11:52:25.530554-0400 objtest [61964:48549108] ***
由于未捕获的异常而终止应用程序
“NSInvalidArgumentException”,原因:“NSLayoutConstraint”
;层=; contentOffset:{0,0}; contentSize:{0,0};
AdjustedContentInset:{0,0,0,0}>:乘数0或零秒
项目以及第一个属性的位置会创建一个
位置等于常数的非法约束。位置
属性必须成对指定。”

如何使用NSLayoutConstraint(或iOS中更好的内置工具)正确对齐?

最佳答案

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

关于ios - 在没有 Storyboard 的情况下将UITableView约束到其父 View 的边缘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45866232/

10-08 22:10
查看更多