ios - 有条件地更改 UITableView 中单元格的高度

标签 ios swift uitableview

我正在表格 View 中制作表格。

假设我有 4 种不同类型的细胞,每一种都是一个具有不同类型答案的问题

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if sortedFixedContentType.count != 0 {
        let item = sortedFixedContentType[indexPath.row]

        switch item.typeId {
        case "1":
            let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath) as! FirstCell
            return cell;

        case "2":
            let cell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath) as! SecondCell
            cell.customDelegate = self
            return cell;
        case "3":
            let cell = tableView.dequeueReusableCell(withIdentifier: "ThirdCell", for: indexPath) as! ThirdCell
            cell.commentsTextView.delegate = self
            return cell;

        case "4":
            let cell = tableView.dequeueReusableCell(withIdentifier: "FourthCell", for: indexPath) as! FourthCell
            return cell;

}

当加载 tableView 时,我只想显示第一个单元格,并且会根据答案显示不同的单元格。

例如:

FirstCell 可以用ABC 来回答,

如果我回答 A SecondCell 将显示答案 XY

如果 X 是答案,将显示 ThirdCell(除了 TextField 没有其他选项),完成后将显示 FourthCell

但是如果在FirstCell中答案是BC只有FourthCell将直接显示。

目前我是通过更改 heightForRowAt 中行的高度来实现的,尽管我认为一定有更简单的方法。 但是我发现了一个问题:

如果我到达 ThirdCell 中的 textField,然后更改我的第一个答案,SecondCell 被隐藏,但 ThirdCell 不是,因为它的条件是第二个答案,它已经做出来了,所以我想将每行的高度设置为条件,但我不知道该怎么做。

所以我有两个主要问题:

  • 是否可以访问 heightForRowAt 以将其设置为条件?

  • 我应该这样做吗?或者也许有更好的方法来获得我需要的东西?我阅读了有关在 TableView 中动态添加和删除行但单元格类型相同的信息,这就是为什么我决定改为按高度隐藏它们的原因。

提前致谢!

最佳答案

我认为传统的方法是不修改高度,而是操作数据源(节中的行数等)来显示/隐藏适当的单元格。

您应该在事件发生后适本地更新数据源,然后在可以使用 func insertRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation)tableView 后立即更新数据源。 deleteRowsAt(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation) 在 tableView 中插入/删除单元格

此文档可能会有所帮助:https://developer.apple.com/documentation/uikit/uitableview/1614879-insertrows

关于ios - 有条件地更改 UITableView 中单元格的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55266955/

相关文章:

ios - 如何创建从 TableView 上的公开指示器到另一个 View Controller 的segue?

ios - 使用 Google iOS SDK 创建多个标记

swift - 从具有私有(private)初始化程序的类继承?

iphone - 后台核心数据加载问题

xcode - 如何使用 Swift 打开我的 OSX 应用程序的父文件夹

swift - 搜索目录中的所有 txt 文件 - Swift

ios - UITableView 快速返回空单元格

ios - 设置所选 tableviewCell 背景颜色的框架在 iOS 7 中工作正常,但在 iOS 6 中不行

iOS - 将 subview 宽度设置为与父 View 相同(objective-c)

javascript - Datatables iOS,Safari 根本不显示