我在包含 UITextView 的表格 View 中有一个单元格。 UITextview 对 uitableviewcell 内容 View 有顶部、前导、尾部和底部的约束。如果 TextView 包含空文本,我想隐藏 uitableviewcell。为此,我将单元格高度降低为 0。由于 TextView 具有关于 UITableViewCell 的约束集。
UITableViewCell
---------------------------
| -T- |
| -L- UITextView -R- |
|_________-B-_____________|
L,T,B,R - 左、上、下、右约束
我遇到了约束问题。
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.
(
"<NSLayoutConstraint:0x7fe5d58753a0 UITableViewCellContentView:0x7fe5d5874fe0.bottomMargin == UITextView:0x7fe5d399c000.bottom>",
"<NSLayoutConstraint:0x7fe5d58753f0 UITableViewCellContentView:0x7fe5d5874fe0.topMargin == UITextView:0x7fe5d399c000.top>",
"<NSLayoutConstraint:0x7fe5d5888a20 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7fe5d5874fe0(0.5)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7fe5d58753a0 UITableViewCellContentView:0x7fe5d5874fe0.bottomMargin == UITextView:0x7fe5d399c000.bottom>
如何隐藏单元格而不影响自动布局。
最佳答案
我会使用 active
属性关闭和打开约束。这是最简单的方法,但请注意,它仅适用于 iOS 8+,因为 NSLayoutConstraint
上的 active
属性仅在 iOS 8 中添加。
首先确保您有一个 IBOutletCollection
数组,其中包含您需要的所有约束:
@IBOutlet var allConstraints : [NSLayoutConstraint]!
如果你有的话,你可以将它们连接到你的 xib/storyboard 中。否则只需在代码中设置它们。
然后,如果您想隐藏单元格,请执行以下操作:
cell.allConstraints.forEach { $0.active = false }
在 TableView 数据源方法 -cellForRowAtIndexPath:
中。
此外,重写单元格子类上的 -prepareForReuse:
方法,如下所示:
override func prepareForReuse() {
super.prepareForReuse()
allConstraints.forEach { $0.active = true }
}
这会重新打开约束,因此如果隐藏单元格被重新用于创建非隐藏单元格,事情就会正确运行。
您可能还需要添加对 setNeedsLayout
和 layoutIfNeeded
的调用,但我会尝试在没有它们的情况下开始 - 希望布局传递在 TableView 的 reloadData
应该为您处理事情 - 如果您不需要,最好不要调用这些函数。
关于ios - 隐藏包含 UITextview 的 UITableviewcell(自动布局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187623/