ios - 基于内容的动态 UITableView 单元格高度

标签 ios objective-c iphone uitableview cocoa-touch

我有一个 UITableView,其中填充了自定义单元格(继承自 UITableViewCell),每个单元格都包含一个基于自动调整大小的 UIWebView在它的内容上。问题是,如何根据内容(变量 webView)更改 UITableView 单元格的高度。

解决方案必须是动态的,因为用于填充 UIWebViews 的 HTML 是从不断变化的提要中解析出来的。

我觉得我需要使用 UITableView 委托(delegate)方法 heightForRowAtIndexPath 但从它的定义来看:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ;//This needs to be variable
}

我无法访问单元格或其内容。我可以更改 cellForRowAtIndexPath 中单元格的高度吗?

任何帮助都会很棒。谢谢。

注意事项

我在 2 年前问过这个问题。随着自动布局的引入,可以找到适用于 iOS7 的最佳解决方案:

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

在 iOS8 上,此功能内置于 SDK 中

最佳答案

这通常效果很好:

objective-C :

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

swift :

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

关于ios - 基于内容的动态 UITableView 单元格高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10287298/

相关文章:

ios - UIImagePickerController 允许我拍摄照片和视频,但不允许我保存它们或 "use"它们

IOS实现单手键盘

IOS模拟器9.0不运行

ios - UINavigationController 在 RCT_EXPORT_METHOD(React Native)中为 nil

ios - 在 UITextField 上点击时将 UIButton 移动到键盘上方

ios - 从 imagePicker 选择图像时,iOS11.2.6、Xcode 9.2 应用程序崩溃

ios - 为什么这条线不能在真正的 iOS 设备上运行?

iphone - 方向应仅针对选定的 View Controller 更改

iphone - 无法识别的选择器发送到实例(使用 UIBarButtonItem)

iphone - 如何在 Xcode 中显示/隐藏 View