ios - 获取 UITableView 每一行的高度

标签 ios swift uitableview

有什么方法可以获取 UITableView 中每一行的行高。我有一个包含动态数据的 UITableView,我正在使用

self.tableView.rowHeight = UITableViewAutomaticDimension

制作动态行高。

但我也想更改整个 UITableView 的高度,为此我需要在重新加载数据后所有行的高度。

我试过用

self.tableView.layoutIfNeeded()
self.tableViewHeightContraint.constant = self.tableView.contentSize.height

但由于未知原因,在我在 UITableView 中添加 3 或 4 条记录后,它给我的高度小于它的实际高度,所以考虑其他方法。计算每一行的高度,然后将它们相加。

我在 Xcode 7.2、iOS 9 和 Swift 2 中做

最佳答案

var dictionaryOfCellHeight = [Int : CGFloat]()
var dataArray = [String]()
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {


    if dictionaryOfCellHeight[indexPath.row] == nil
    {
    var frame : CGRect = tableView.rectForRowAtIndexPath(indexPath)

        if indexPath.row == dataArray.count
        {

            dictionaryOfCellHeight[indexPath.row] = frame.size.height
            //calculate total height and reload table
        }
        else
        {
        dictionaryOfCellHeight[indexPath.row] = frame.size.height
        }

    }
}

关于ios - 获取 UITableView 每一行的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34899686/

相关文章:

ios - EKCalendar 没有成员 defaultCalendarForNewReminders

iphone - 在 iOS 7 中取消 UITableViewCell 滑动删除时收到通知

ios - 如何在 UITableView 滚动时保持 UITableViewCell 的状态?

ios - 迁移到 swift 3 和 Xcode 8 时 cocoa pods 错误的解决方案是什么,问题详情在描述中?

iphone - 如何将多个 UIBarButton 项目添加到导航栏?

ios - 使用 SKPhysics body 检测碰撞

xcode - 无法将 IBAction 连接到 xib 的 TableView

ios - 自定义 UIButton 的 subview 不在正确的位置

swift - 如何摆脱 "% is unavailable: Use truncatingRemainder instead"?

ios - UITableView 过滤