ios - 动态表格 View 单元格,以编程方式更改 subview 高度

标签 ios xcode swift uitableview autolayout

我有一个带有自定义 View 单元格的 UITableViewCell。 在这个 View 单元格中,我有一个名为 imgWrapper 的简单 UIView,我在其中添加了如下约束:

  • 宽度 = 50
  • 高度 = 50
  • 导致 super View = 20
  • top to superview = 20
  • 底部到 super View = 20

这些是那里唯一的限制。我将拥抱和压缩保留为默认值。

在我的代码中我设置了这个:

  override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 90
}

然后在我的 rowAtIndex 中...我有这个:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: LogCustomCell = tableView.dequeueReusableCellWithIdentifier("logCustomCell", forIndexPath: indexPath) as! LogCustomCell

     var imgWrapperHeight: CGFloat = log.big ? 100 : 50

     cell.imgWrapperHeight.frame.size.height = imgWrapperHeight 
     return cell
}

一旦我编译并运行它。所有单元格的大小都相同。

注意事项:

  • 我检查了 log.big 是否为真/假,它确实发生了变化。
  • 我也尝试过 CGRect(x,y,width,height) 但还是没用。
  • 我知道我可以做 heightForRowAtIndexPath 但我想做动画而且我知道我们可以为标签做这样的事情(见打印屏幕)这使得 tableView 知道高度而无需定义它:<

enter image description here

知道我做错了什么吗?

最佳答案

您需要将高度逻辑放入名为 tableView:heightForRowAtIndexPathUITableViewDelegate 方法中,如下所示:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return (true ? 100 : 50) + 2 * 20
}

附言。我是用 Swift 2 编写的,因此使用了 override 关键字。

关于ios - 动态表格 View 单元格,以编程方式更改 subview 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32622704/

相关文章:

ios - 如何在 iOS 中滑动 ion slide 时禁用垂直滚动?

ios - Objective-C 常量 : Xcode build failure for simulator while success in iPhone

iphone - 为什么 Xcode 让我的 Localized.strings 文件看起来像这样搞砸了?

ios - Unity IOS 中的谷歌播放服务错误

使用 firebase block 编译的 Swift 关闭

iOS xcode 按钮未链接。

ios - 如何替换 UITextView 中的特定字符

ios - 读取 iOS Webkit 崩溃堆栈跟踪

ios - 自定义底部栏过渡到 Swift 中的另一个 View ?

arrays - 将 Firestore 数据加载到 TableView Swift 4