首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tableView heightForRowAtIndexPath不工作

tableView heightForRowAtIndexPath不工作
EN

Stack Overflow用户
提问于 2016-03-10 19:32:13
回答 1查看 8.2K关注 0票数 2

我有表格视图来显示用户的评论。

我需要根据内容高度使每一行的高度动态。

我搜索了它,我发现

heightForRowAtIndexPath

但它不起作用,否则我不知道怎么用它!

这是我的密码:

代码语言:javascript
复制
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
   let username = cell.viewWithTag(1) as! UILabel

    let comment = cell.viewWithTag(2) as! UITextView
    username.text = usernames[indexPath.row]

    comment.text = comments[indexPath.row]

    return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.comments.count
}

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-10 20:25:01

您没有正确实现heightForRowAtIndexPath方法。你应该阅读自定尺寸表视图单元格,因为它会做你想做的事情。

基本上,要使用自调整大小的单元格,您将为UITableView设置一个估计行高,并将rowHeight设置为UITableViewAutomaticDimension值(或者SWIFT4.2或更高版本中的UITableView.automaticDimension )。

Swift 4.2之前的

代码语言:javascript
复制
tableView.estimatedRowHeight = 85.0
tableview.rowHeight = UITableViewAutomaticDimension

Swift 4.2:

代码语言:javascript
复制
tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableView.automaticDimension

将估计的行高值设置为接近所有单元格的粗平均高度的值。这有助于iOS了解完整的UIScrollView内容有多大。

此外,对于自调整大小的单元格,您将根本不实现heightForRowAtIndexPath。每个单元的高度都是从每个单元内的约束中获得的。

要获得关于自调整大小单元格的良好指南,请查看本教程

如果不想进行自调整大小的单元格,可以实现heightForRowAtIndexPath,但需要返回每个单元格的正确高度。这个逻辑将由您根据indexPath参数来确定。但您需要确保以像素(逻辑像素)为单位返回每个单元格(由indexPath指定)的高度。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35925574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档