【发布时间】:2013-12-10 03:16:11
【问题描述】:
我对 iOS 编程相当陌生,可能不了解视图层次结构,因此无法在我创建的自定义表格单元格类中成功获取两个标签以正确调整大小。即"translatesAutoresizingMaskIntoConstraints" 属性让我有点困惑。
我没有为这部分代码使用故事板:我有一个 TableViewController,我在 viewDidLoad 中创建了我自己的 tableView。在cellForRowAtIndexPath 中,我初始化了我自己的TableViewCell 实现。
我遇到的问题是,当我将表视图的 "setTranslatesAutoresizingMaskIntoConstraints" 设置为 NO 和我创建的 UILabels 然后添加我的约束时,我收到以下错误:
"Terminating app due to uncaught exception `'NSInternalInconsistencyException',` reason: 'Auto Layout still required after executing `-layoutSubviews`. UITableView's implementation of `-layoutSubviews` needs to call super.'"
如果我注释掉 setTranslatesAutoresizingMaskIntoConstraints 行,我的应用程序会运行,但是我会收到以下关于约束的警告:
“不能同时满足约束。可能至少有一个 以下列表中的约束是您不想要的。尝试 这个:(1)查看每个约束并尝试找出你 不要期待; (2) 找到添加了不需要的约束的代码或 约束并修复它。 (注:如果你看到
NSAutoresizingMaskLayoutConstraints不明白的可以参考UIView属性的文档translatesAutoresizingMaskIntoConstraints)"
基本上我想要做的是在此处输入代码,使两个标签彼此齐平,并根据方向/设备调整它们的大小(我将在它们上设置背景颜色,因此希望它们看起来“连续” )
谁能帮我解释一下我错过了什么?提前致谢。
我添加标签的代码是:
self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 30.0f)];
self.nameLabel.textColor = [UIColor redColor];
self.nameLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:12.0f];
self.nameLabel.backgroundColor = [UIColor brownColor];
[self.nameLabel setText:@"Test"];
// [self.nameLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.contentView addSubview:self.nameLabel];
...
NSDictionary *viewsDictionary =
NSDictionaryOfVariableBindings(nameLabel, summaryLabel);
NSArray *constraints =
[NSLayoutConstraint constraintsWithVisualFormat:@"|-[nameLabel][summaryLabel]-|"
options:0
metrics:nil
views:viewsDictionary];
【问题讨论】:
-
您的
updateConstraints方法和您的layoutSubviews方法会发生什么?你打电话给[super layoutSubviews]? -
hmm,根据这个:developer.apple.com/library/ios/documentation/UserExperience/… 你不应该调用 setTranslatesAutoresizingMaskIntoConstraints:NO(见文章最后一段)
-
感谢@Evan,但是我没有在我创建的自定义单元类中覆盖这些方法,因此不确定错误是什么..
-
@Yohst:我看到了,这是否意味着我不能在自己的表格单元实现中使用自动布局?我希望我误解了这一点。
-
我不认为你应该为表格视图设置 translatesAutoresizingMaskIntoConstraints 为 no,只为标签设置。
标签: ios objective-c uitableview uilabel autolayout