ios - Swift 什么是替换 TableViewCell 中内容的最佳方法

标签 ios swift tableview

我想在 GIF 中做一些类似的事情 我尝试了 2 种方法,一种是在选择行时隐藏元素并显示其他元素,但这不是很优雅而且效果不佳 第二个是创建 2 个 View ,一个带有标签,另一个带有按钮,将它们作为 subview 添加到 cell.contentView 但这会导致其他单元格出现一些问题,因为它们显示错误的数据。我怎样才能重新创建这样的东西?

enter image description here

最佳答案

我认为这样的事情会起作用:

  1. 使用 2 个不同的 UITableViewCells:将它们添加到 Storyboard中的 TableView 并单独设计它们,也可以为它们使用 2 个不同的 UITableViewCell 子类

  2. 在 TableView 的数据源类中有一个数组,该数组将定义每一行的单元格类型(例如,最简单的解决方案是一个整数数组,其值:0 代表第一个单元格,1 代表第二个单元格单元格)

  3. 用每一行的 0 初始化该数组

  4. tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 中:

    • if cellTypes[indexPath.row] == 0 --> 返回第一种类型的单元格
    • if cellTypes[indexPath.row] == 1 --> 返回第二种类型的单元格
  5. tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 中:

    • 切换数组中的单元格类型
    • 用动画重新加载行,例如您可以使用 .fade 或 .left 或 .right 等。

tableView.reloadRows(at: [indexPath], with: .fade)

编辑:您的解决方案也是一个很好的解决方案,但是当单元格出队时可能会导致问题,因此如果出队的单元格具有错误的 subview ,那么您需要在 cellForRowAt indexPath< 中将 subview 切换回来 数据源方法。

EDIT2:我花了一些时间在 Xcode 中尝试了我的解决方案。这是我的 tableview Controller 的代码:

class TableViewController: UITableViewController {

    private var cellTypes: [Int] = [1, 1, 1, 1, 1, 1]

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

    public override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 56.0
    }

    public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.cellTypes[indexPath.row] == 1 {
            return tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath)[![enter image description here][1]][1]
        } else {
            return tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
        }
    }

    public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        if self.cellTypes[indexPath.row] == 1 {
            self.cellTypes[indexPath.row] = 2
            tableView.reloadRows(at: [indexPath], with: .fade)
        } else {
            self.cellTypes[indexPath.row] = 1
            tableView.reloadRows(at: [indexPath], with: .right)
        }
    }

}

这是它在 iOS 模拟器中的工作方式:

enter image description here

关于ios - Swift 什么是替换 TableViewCell 中内容的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503648/

相关文章:

ios - 条件 TableView 单元格显示

iphone - 更改方向时如何正确调整 UIView 的大小?

swift - MLMediaLibrary - 显示照片库 -Swift 代码错误 - macOS

ios - 如果 subscribeOn 背景,RxSwift TestScheduler 不工作

php - Swift 不解析来自 PHP 服务器的 JSON

ios - 稍后调用 tableView cellForRowAtIndexPath

ios - TableView 上的多个单元格选择

ios - 从服务器快速加载数据iOS

ios - 声明计算变量后,编译器开始提示类没有初始化器

iphone - 如何找出屏幕方向,纵向还是横向?