我有一个非常简单的观点,即我无法终生解决问题。我已经成功地将自动布局和 systemLayoutSizeFittingSize
用于相当复杂的自定义 UITableViewCells
。这是我第一次将它用于 UIView
(将在 UITableView.tableHeaderView
中使用),我无法让它工作。
我在 View 中有一个简单的标签,我想覆盖整个 View 。我已将 Trailing
、Leading
、Top
和 Bottom
约束添加到父级对应边的标签中。当我这样做时,systemLayoutSizeFittingSize
计算出正确的 height
,但我收到以下错误:
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x7fbb71d9a310 V:|-(5)-[UILabel:0x7fbb71df5120'Test Label'] (Names: '|':mailapp.MailTableHeaderView:0x7fbb71d2c490 )>",
"<NSLayoutConstraint:0x7fbb71d2ebf0 UILabel:0x7fbb71df5120'Test Label'.bottom == app.HeaderView:0x7fbb71d2c490.bottom - 5>",
"<NSLayoutConstraint:0x7fbb71de31d0 V:[app.HeaderView:0x7fbb71d2c490(0)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7fbb71d2ebf0 UILabel:0x7fbb71df5120'Test Label'.bottom == app.HeaderView:0x7fbb71d2c490.bottom - 5>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
现在,如果我删除标签上的“底部”约束,自动布局可以正常工作,但现在 systemLayoutSizeFittingSize
返回 0。
什么是既能使约束满足自动布局引擎又能使 systemLayoutSizeFittingSize
计算正确大小的正确方法?
正如我提到的,最令人困惑的是我已经成功地将它用于复杂的自动布局,但我注意到所有这些都是 UITableViewCells
。我不确定是否有区别。
最佳答案
我想出了问题,但我不明白为什么。对于 UITableViewHeader,我无法为 View 执行典型的自动布局操作。也就是说,我必须将 translatesAutoresizingMaskIntoConstraints
设置为 true
。实际上,我不能为标题 View 使用自动布局,我必须手动设置框架。
在标题 View 中,我可以成功地为 subview 使用自动布局。
所以我的算法是这样构建tableHeaderView
的:
- 使用任意框架创建标题 View
- 计算(标题 View 的 subview 的)约束
- 设置标题 View 的
frame.width
以匹配父tableView.frame.width
- 布局标题 View
- 使用
systemLayoutSizeFittingSize
计算高度 - 更新标题 View 的
frame.height
这对我有用。如果我在 translatesAutoresizingMaskIntoConstraints
设置为 false
的情况下创建 header View ,我将无法让它工作。
关于ios - 使用自动布局和 systemLayoutSizeFittingSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28336262/