ios - 使用 AutoLayout 将 UIView 隐藏在单元格内时,UITableViewCell 高度不合适

标签 ios swift uitableview autolayout

我已经为这个问题苦苦挣扎了 3 天,仍然无法弄清楚。我希望这里的任何人都可以帮助我。

目前,我有一个带有自定义单元格(UITableViewCell 的子类)的 UITableView。在这个自定义的单元格中,有许多 UILabel,并且所有这些都正确设置了自动布局(固定到单元格内容 View )。这样,无论 UILabel 是长文本还是短文本,单元格高度都可以显示适当的高度。

enter image description here

问题是,当我尝试将其中一个 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()

目前结果如下(单元格高度错误): enter image description here

如图 2 所示,UILabel 6 可能包含长文本,当我隐藏此 View 时,内容 View 仍显示为隐藏前的大小。 请指出我错在哪里,我将不胜感激。

最佳答案

我终于改了代码

tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)

以下内容

tableView.reloadData()

然后,它就完美地工作了。 但是,我真的不知道它的确切原因。希望有人仍然可以评论出来。

关于ios - 使用 AutoLayout 将 UIView 隐藏在单元格内时,UITableViewCell 高度不合适,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930129/

相关文章:

objective-c - 在没有动画的情况下在 iOS 中显示键盘

iphone - MKMapView initWithFrame 不使用 ARC 释放内存

objective-c - 我的 UITableView 总是回到顶部

ios - UIPageViewController EdgeInset 问题中的 UITableView

objective-c - 单击 uitableview 单元格后获取相同的数据

ios - iOS 中通过推送通知检测应用程序是否未打开?

ios - 属性上的 Xcode 属性与从 'UIViewController' 继承的属性不匹配

xcode - 如何分析 Swift 框架?

ios - Swift Animation - 启动画面标志向上滑入登录屏幕上的标志

swift - 用于滚动的 UIGesture 识别器?