【问题标题】:Set tableview cell row height dynamically?动态设置tableview单元格行高?
【发布时间】:2016-10-19 20:05:08
【问题描述】:

我有一个带有标签和图像的表格视图。在某些单元格中,没有图像,因为我使用 imageView.removeFromSuperview() 将其从单元格中删除。当单元格中有图片时,行高为445,“自定义”勾选。

如何根据标签的长度而不是删除 imageview 后 imageview 的长度/大小来动态设置行高?

【问题讨论】:

    标签: xcode swift uitableview uiimageview tableviewcell


    【解决方案1】:

    如果你想要动态的行高,你可以定义你的约束(确保它们是明确的),将标签的numberOfLines 设置为零,然后在viewDidLoad 中,告诉它行应该自动调整它们的高度:

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 44
    

    如果你也想隐藏/显示UIImageView,我必须承认我对removeFromSuperview 方法并不疯狂(因为当单元格被重复使用时,你必须重新添加图像视图,并可能重建其约束)有几个选项:

    1. 对于带有图像视图的单元格和不带图像视图的单元格,您可以使用不同的单元格原型。那么cellForRowAtIndexPath只需要实例化正确的单元格即可。

    2. 您可以继续定义一套完整的约束条件,这些约束条件对于图像的存在和没有图像都是明确的。然后,您可以 activate 约束并将图像视图设置为 hidden

      override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
      
          let image = ...  // let's say it was an optional, set if needed, left `nil` if not
      
          cell.customImageView?.image = image
      
          if image == nil {
              cell.customImageView.hidden = true
              cell.imageBottomConstraint.active = false
      
              cell.customLabel.text = ...
          } else {
              cell.customImageView.hidden = false
              cell.imageBottomConstraint.active = true
          }
      
          return cell
      }
      

      当具有决定单元格高度的相互竞争的约束集时,诀窍是确保它们具有不同的优先级和/或它们使用不等式,因此如果两个集都有效,则不会出现无法满足的冲突(例如图像视图可能具有更高的优先级)。

    3. 如果需要,您可以使用“老派”并以编程方式确定标签字段的大小,然后实现 heightForRowAtIndexPath,但自动布局使此过程变得不必要。

    【讨论】:

    • 我应该为imageBottomConstraint 输入什么内容才能使其成为“底部空间:superview。等于 8”?
    • imageBottomConstraint 只是一个 IBOutlet 我在 IB 中连接到底部约束。
    【解决方案2】:

    你需要重写这个方法:

    Override func tableview(tableview:UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {}
    

    在此方法中返回您想要的 indexPath 的所需高度

    【讨论】:

      【解决方案3】:

      如果您使用的是 UILabel,它有一个带有高度属性的框架。

      和 heightForRowAtIndexPath,应该涵盖您想要使用的适当方法: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/#//apple_ref/occ/intfm/UITableViewDelegate/tableView:heightForRowAtIndexPath:

      不确定您的图像当前是如何设置的,但这里有一个粗略的示例:

          override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
              if image != nil {
                  return 445.0
              else {
                  label.frame.height (or whichever value you'd prefer)
              }
      }
      

      【讨论】:

      • label.frame.height 不起作用。我需要根据标签的大小设置行高。
      猜你喜欢
      • 2015-08-01
      • 2017-11-14
      • 2021-12-23
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多