【问题标题】:tableView not setting automatic row heighttableView 未设置自动行高
【发布时间】:2023-03-23 03:32:01
【问题描述】:

在我的项目中,我有一个包含 3 个部分的静态 tableView。第二部分中的单元格包含一个动态填充的标签,因此具有动态高度。单元格应将其高度调整为标签的高度。这是我尝试过的,但没有成功:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.section == 0 {
      return 44
    } else if indexPath.section == 1 {
      return UITableViewAutomaticDimension
    } else if indexPath.section == 2 {
      return 80
    } else {
      return 50
    }
}

除自动尺寸外,所有部分的高度均已正确设置。有什么帮助吗?

【问题讨论】:

  • 更多信息会很有用 - 您是否为您的单元设置了所有约束?您是否正确设置了标签(即 numberOfLines = 0, lineBreakMode)?
  • 我将标签的约束设置为左10、前10和右10。标签有0行和默认的lineBreakMode(Truncate Tail)。这里有什么要改变的吗?
  • 是的,你希望 lineBreakMode 是自动换行! 0 行是正确的,你需要有一个多行标签。

标签: ios swift tableview row-height


【解决方案1】:

viewDidLoad()中设置这一行

tableView.rowHeight = UITableViewAutomaticDimension

然后写这个table view方法

 func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        return UITableViewAutomaticDimension
    }

还要确保您正确使用了auto layout。 你已经设置了number of lines for lable = 0

【讨论】:

  • 不幸的是,这不起作用,也许与自动布局有关?我只为单元格内的标签设置约束(左 10、前 10、右 10)并将行设置为 0。
  • 请给出底部约束
  • 做到了。谢谢!
  • 欢迎。不要犹豫,给你评分
【解决方案2】:

您还需要提供估计的行高。您可以通过使用UITableViewestimatedRowHeight 属性或实现相应的委托方法来做到这一点:

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return XXXXX // Provide your estimation here, or pass UITableViewAutomaticDimension (not the best for performances)
}

参考:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithSelf-SizingTableViewCells.html

【讨论】:

    猜你喜欢
    • 2015-08-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2013-09-11
    • 2021-09-18
    • 2016-10-19
    • 2023-03-27
    相关资源
    最近更新 更多