tableView 没有设置自动行高

tableView not setting automatic row height

在我的项目中,我有一个包含 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
    }
}

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

您还需要提供估计的行高。您可以通过使用 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

viewDidLoad()

中设置此行
tableView.rowHeight = UITableViewAutomaticDimension

然后写这个table view方法

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

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