【问题标题】:UITableView with dynamic height with auto layout constraints [duplicate]具有自动布局约束的动态高度的 UITableView [重复]
【发布时间】:2016-12-02 06:13:05
【问题描述】:

我有一个表格视图,其中cells 使用自动布局constraints 动态增长。我有一个场景,我必须在其中一个动态构造的单元格中显示UITableView。这里主要的是我不知道任何东西的框架,我必须使用约束来构造所有东西。我需要的只是解释如何实现这一点?

【问题讨论】:

标签: ios uitableview dynamic autolayout nslayoutconstraint


【解决方案1】:

所以我猜你有一个 MasterViewController 里面有一个 tableView。然后你想在 MasterViewController 的 tableView 的一个单元格中添加另一个 tableView,它是 MyCustomcell 类的一部分。

用tableView添加customCell没什么大不了的,但是根据CustomCell中要显示的数据计算和维护MasterViewController的高度有点棘手。如果您只是询问如何在 tableView 中添加 CustomCell,那么您可以通过快速谷歌轻松获得许多好的教程。

我遇到了类似的情况并通过以下方式解决了问题。希望这会有所帮助。

1) 如果您有一个 customCell,您只需要在其中显示文本。然后 MasterViewController 的 tableView 的高度可以很容易地根据文本的内容自动保持自动布局。 This tutorial 有很好的解释。

2) 如果您在 MasterViewcontroller tableView 的一个单元格中添加 tableView,那么它会变得很棘手。现在 MasterViewController 的单元格高度取决于 CustomCell 表格视图高度的高度内容。我试图通过在 Swift 3 中应用不同的方式来处理这种情况,但最终通过以下方式得到了结果:-

class MasterViewController: UIViewController {
          @IBOutlet weak var tableView: UITableView!

          var customCell:MyCustomCell? = nil

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as! MyCustomCell
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        customCell = cell
        return cell
    }

}

extension MasterViewController:UITableViewDelegate{

     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

         if let aHeight = customCell?.tableView.contentSize.height{
             return aHeight
         }

         return 0

     }

}

【讨论】:

  • 我必须对 UITableView(在 UITableViewCell 内)应用哪些约束?
  • 你可以只添加lead、trail、top、bottom到0。
  • 我做到了,但 tableview 的高度现在为零。
  • 尝试重新加载 MaterViewController 的表格,或者您可以在填充完 MyCustomCell 中的数据后重新加载添加 tableView 的单元格。在我的情况下,我在 MyCustomCell 中请求了数据,在数据请求完成并且单元格已填充数据后,MasterViewController 中的 tableview 已重新加载。
  • 您能否分享一个示例项目,说明如何最好在 github 中实现这一目标
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
  • 1970-01-01
  • 2023-03-17
  • 2017-12-24
  • 2020-06-05
  • 1970-01-01
相关资源
最近更新 更多