iOS 8 UITableView第一行的高度错误

Dev*_*s50 8 objective-c uitableview uilabel ios swift

我正在开发一个应用程序,我面临一个奇怪的问题.我在故事板中创建了一个UITableViewController,并添加了一个原型单元格.在这个单元格中,我添加了一个UILabel元素,这个UILabel占据了整个单元格.我已经使用自动布局进行了设置,并添加了左,右,顶部和底部约束.UILabel包含一些文本.

现在在我的代码中,我初始化表视图的rowHeight和estimatedRowHeight:

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 50
}
Run Code Online (Sandbox Code Playgroud)

我按如下方式创建单元格:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("HelpCell") as? UITableViewCell
    if(cell == nil) {
        cell = UITableViewCell(style: .Default, reuseIdentifier: "HelpCell")
    }
    return cell!
}
Run Code Online (Sandbox Code Playgroud)

我在表视图中返回两行.这就是我的问题:第一行的高度是大的.似乎第二排,第三排等都具有正确的高度.我真的不明白为什么会这样.有人可以帮我弄这个吗?

Sak*_*boy 17

我有一个问题,在第一次加载时细胞的高度不正确,但在上下滚动后,细胞的高度是固定的.

我为这个问题尝试了所有不同的'修复',然后最终发现在最初调用之后调用这些函数self.tableView.reloadData.

            self.tableView.reloadData()
            // Bug in 8.0+ where need to call the following three methods in order to get the tableView to correctly size the tableViewCells on the initial load.
            self.tableView.setNeedsLayout()
            self.tableView.layoutIfNeeded()
            self.tableView.reloadData()
Run Code Online (Sandbox Code Playgroud)

只在初始加载后执行这些额外的布局调用.

我在这里找到了这个非常有用的信息:https://github.com/smileyborg/TableViewCellWithAutoLayoutiOS8/issues/10

更新: 有时您可能还必须完全配置您的单元格heightForRowAtIndexPath,然后返回计算的单元格高度.查看此链接以获得一个很好的例子,http://www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout,特别是部分内容heightForRowAtIndexPath.

更新2:我还发现非常有利于覆盖estimatedHeightForRowAtIndexPath并提供一些准确的行高估计.如果您的UITableView单元格可以是各种不同的高度,这将非常有用.

这是一个人为的示例实现estimatedHeightForRowAtIndexPath:

public override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    let cell = tableView.cellForRowAtIndexPath(indexPath) as! MyCell

    switch cell.type {
    case .Small:
        return kSmallHeight
    case .Medium:
        return kMediumHeight
    case .Large:
        return kLargeHeight
    default:
        break
    }
    return UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)

更新3: UITableViewAutomaticDimension已经修复了iOS 9(呜呜!).所以你的细胞应该自动调整大小,而不必手动计算细胞高度.