【问题标题】:How to change height of UITableViewCell when constraint changes?约束改变时如何改变 UITableViewCell 的高度?
【发布时间】:2018-07-13 17:00:03
【问题描述】:

我的问题与这个有关:How to change height Constraint of UIView in UitableviewCell when using UITableViewAutomaticDimension

那里的解决方案似乎对我不起作用。

在上图中,我有一个简单的单元格。 在点击单元格时,我想将 redView 的约束更改为更大。这应该会自动改变单元格的高度。

我已经将单元格的高度限制设置为@IBOutlet,我认为我正确地更改了单元格的大小,但它不起作用。

这是我无法运行的示例应用程序。有什么帮助吗? SampleApp - for Xcode 9.3

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    您需要为红色视图设置底部约束,以便自动布局可以在设置常量值后拉伸单元格

    extension ViewController: UITableViewDataSource, UITableViewDelegate {
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 1
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "c", for: indexPath) as! customcell
            configure(cell: cell, indexPath: indexPath)
            cell.redview.backgroundColor = .red
            cell.selectionStyle = .none
            return cell
        }
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let cell = tableView.cellForRow(at: indexPath) as! customcell
            cell.constraint.constant = data[indexPath.row] == "contracted"  ? 30 : 200
            data[indexPath.row] = data[indexPath.row] == "contracted" ? "expanded" : "contracted"
            tableView.reloadData()
        }
    
        func configure(cell: customcell, indexPath: IndexPath) {
            let data = self.data[indexPath.row]
            if data == "expanded" {
                cell.constraint.constant = 200
            } else {
                cell.constraint.constant = 30
            }
    
            cell.layoutIfNeeded()
        }
    }
    

    【讨论】:

    • 你必须这样做,他给出了一个冲突,因为他建议在自动布局根据内容建立正确高度之前预先高度,你可以将这个底部约束的优先级设置为 999防止冲突日志
    • in else you set it to 30 try to make it say 300 and check ??
    • 您是否在我上面提供的示例 zip 文件中尝试过这个?它不起作用:(这是我根据您所说的更新的项目-> github.com/patchthecode/JTAppleCalendar/files/2194962/test.zip
    • 是的,尝试过并且有效,您在数组中将数据设置为 Contacted 以便 else 在您将约束常量设置为 30 的地方运行,您可能会错误地认为 if 将以常量 200 运行
    • @Sh_Khan 如果只是尺寸变化,那么beginUpdates & endUpdates 组合优于您的解决方案。重新加载整个表通常会产生其他严重影响。 layoutIfNeeded 无论如何都不需要。
    【解决方案2】:

    调用下面将重新计算高度。

    [tableView beginUpdates];
    [tableView endUpdates];
    

    【讨论】:

    • 这取决于你如何触发高度变化。如果它在单元格内完成,您可能需要对表格视图控制器进行委托回调,因为单元格没有 tableView 引用。喜欢stackoverflow.com/questions/1110482/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 2018-01-10
    • 1970-01-01
    • 2019-05-31
    相关资源
    最近更新 更多