【问题标题】:Can't change row height in Xcode 6 dynamic table无法更改 Xcode 6 动态表中的行高
【发布时间】:2015-08-04 22:29:39
【问题描述】:

我有一个 UItableViewController 并希望行高适应 UITextView 中的文本。如果我在 viewDidLoad 中使用此代码,它会使行的高度太小而无法容纳文本:

 self.tableView.rowHeight = UITableViewAutomaticDimension   
 self.tableView.estimatedRowHeight = 50

我能找到调整大小的唯一方法是更改​​ StoryBoard 中的表视图行高。这会更改表格视图中的每个单元格,这不是我想要的。

有人对我缺少的东西有什么建议吗?

【问题讨论】:

  • 如果 UITableViewAutomaticDimension 不能正常工作,这意味着您的单元格约束没有完全满足,因此没有按照您的意愿呈现。
  • 据我所知,我的约束是正确的。我已将 textview 的顶部和底部固定到单元格的边缘。同一单元格中的开关仅固定在顶部。

标签: swift uitableview xcode6


【解决方案1】:

这是我的工作代码:

override func tableView(tableView: UITableView,
    heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        var text:String
        if indexPath.section > 0 {
            text = switchNameArray [indexPath.row]
        } else {
            text = viewDescription
        }
        return calculateHeight(text)
}

func calculateHeight (text:String) -> CGFloat {
    if UIDevice.currentDevice().userInterfaceIdiom == .Pad
    {
        return CGFloat(count(text)+50) // iPad
    } else {
        return CGFloat(count(text)+30) // iPhone
    }
}

【讨论】:

    【解决方案2】:

    有一个覆盖方法可以改变每行的高度。

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

    如果你想让它更大或更小,你也可以创建 if-Else 条件。只需返回一个数字

    【讨论】:

    • 按照 wherisleo 和 @caleb 的建议,我设法使单元格高度大致正确。我将在我的答案中包含代码。
    【解决方案3】:

    您可以尝试使用:

    func tableView(tableView: UITableView,
        heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    
            return 100 //Whatever fits your need for that cell
    }
    

    您可以使用 tableView.cellForRowAtIndexPath(indexPath) 获取单元格并根据需要设置高度。

    【讨论】:

    • 我不想计算每个单元格的大小。除此之外,我的应用是通用的,所以它变得非常复杂。
    • 单元格的高度很可能非常相似,如果不是在所有设备上都相同的话。一个简单的修复,因为约束不让它自动调整大小,只是使高度略大于 textView 的高度。只需返回单元格的 textView.height + 10 或任何您想要的填充。
    • 鉴于我已将边缘固定到它,textView 高度不是单元格高度的函数吗?
    • 对。尽量不要固定边缘,只需使用自动布局告诉您使用的任何内容。只有当 textView 根据里面的文本调整大小时, AutomaticDimension 才会改变。在模拟器上运行时,您还可以通过按 Debug View Hierarchy 来检查高度。
    • 到目前为止我所阅读的所有内容都表明 textView 应该固定在单元格的边缘。这是错的吗?
    【解决方案4】:

    如果您希望它适应您内容的大小 获取当前tableView框架然后调整高度 取决于内容的高度。

    var frame = CGRect(origin: tableView.frame.origin, size: tableView.frame.size)
    
    frame.size.height = tableView.contentSize.height
    tableView.frame = frame
    

    【讨论】:

    • 这会改变整个视图的高度,OP想改变表格行的高度。
    猜你喜欢
    • 2020-05-04
    • 2023-03-21
    • 2017-02-23
    • 2015-01-13
    • 2014-11-23
    • 2012-11-11
    • 2017-05-21
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多