【问题标题】:Swift 3: UITableView row height changes due to UINavigationViewControllerSwift 3:由于 UINavigationViewController 导致 UITableView 行高发生变化
【发布时间】:2016-11-28 14:20:05
【问题描述】:

我在UINavigationController 中嵌入了一个 UIViewController。我的UIViewController 包含一个UITableView,它有两种类型的单元格:单元格1(第一个单元格)的高度=250,单元格2 的高度=85。一开始一切正常,但是当我用胶带记录一个单元格以显示其细节时使用self.navigationController?.pushViewController(vc, animated: true),然后当我返回parentViewController(包含UITableView)时,cell1 的高度是cell2。在情节提要中,我将表格的 rowHeight 设置为 250,对于 cell1 的视图,我设置了 250,对于 cell2,我设置了 85。然后在控制器中,我将 table.rowHeight 设置为 index.row 的功能,你可以见上面的代码:

// MARK: - Table view

    private func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }


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


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 if indexPath.row == 0 {
            tableView.rowHeight = 260
            var cell = tableView.dequeueReusableCell(withIdentifier: "homeFirstTableViewCell") as? HomeFirstTableViewCell
//set the content of the cell
} else {
            tableView.rowHeight = 85
            var cell = tableView.dequeueReusableCell(withIdentifier: "homeTableViewCell") as? HomeTableViewCell
}
}

注意:

我只在 iOS 8 设备上遇到这个问题

编辑:

当我尝试这个时:

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

        if(indexPath.row == 0 ){
            return 260
        }

        return 85
    }

以cell2为类型的第一个单元格得到cell1的高度

【问题讨论】:

  • 你应该实现func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat来设置行高

标签: ios swift uitableview uinavigationcontroller


【解决方案1】:

您需要在情节提要或 xib 中设置单元格内容的约束(如果您在一个中创建它们),执行此操作的一种方法是创建 containerView 并为其分配高度约束,然后使用它方法

tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat

而不是这个

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

并返回一个介于 85 和 250 之间的抽象数

【讨论】:

  • 当我这样做时,所有的单元格都得到了 cell1 类型的高度 (250)
  • 您是否添加了内容视图并为您的两个单元格分配了高度约束?
  • 是的,我已经有一个内容视图,cell1 的高度 = 250,cell2 的高度 = 85
猜你喜欢
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 2022-01-13
  • 2016-04-01
  • 1970-01-01
  • 2010-09-30
相关资源
最近更新 更多