我已经为这个问题苦苦挣扎了 3 天,仍然无法弄清楚。我希望这里的任何人都可以帮助我。
目前,我有一个带有自定义单元格(UITableViewCell 的子类)的 UITableView。在这个自定义的单元格中,有许多 UILabel,并且所有这些都正确设置了自动布局(固定到单元格内容 View )。这样,无论 UILabel 是长文本还是短文本,单元格高度都可以显示适当的高度。
问题是,当我尝试将其中一个 UILabel(底部的)设置为隐藏时,内容 View 未相应地调整高度,单元格也是如此。
我的不足是我从 Interface Builder 添加了一个 Hight Constraint 到底部标签,并带有以下内容。
Priority = 250 (Low)
Constant = 0
Multiplier = 1
这使虚线约束。然后,在 Swift 文件中,我输入了以下代码。
override func viewDidLoad() {
super.viewDidLoad()
//Setup TableView
tableView.allowsMultipleSelectionDuringEditing = true
//For tableView cell resize with autolayout
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! RecordTableViewCell
cell.lbLine.hidden = !cell.lbLine.hidden
if cell.lbLine.hidden != true{
//show
cell.ConstrainHeightForLine.priority = 250
}else{
//not show
cell.ConstrainHeightForLine.priority = 999
}
//tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
return indexPath
棘手的事情是,当我调用 tableView.reloadRowAtIndexPaths() 时,单元格会显示正确的高度,但有一个错误,它必须通过双击(选择)同一单元格来触发行而不是单击。
为此,我还尝试在 willSelectRowAtIndexPath 方法中执行以下代码,但它们都不起作用。
cell.contentView.setNeedsDisplay()
cell.contentView.layoutIfNeeded()
cell.contentView.setNeedsUpdateConstraints()
如图 2 所示,UILabel 6 可能包含长文本,当我隐藏此 View 时,内容 View 仍显示为隐藏前的大小。 请指出我错在哪里,我将不胜感激。
最佳答案
我终于改了代码
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
以下内容
tableView.reloadData()
然后,它就完美地工作了。 但是,我真的不知道它的确切原因。希望有人仍然可以评论出来。
关于ios - 使用 AutoLayout 将 UIView 隐藏在单元格内时,UITableViewCell 高度不合适,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930129/