swift - 在 Swift 中保存 UITableViewCell 复选标记选择

标签 swift uitableview

我正在尝试使用类似于“设置”->“常规”->“自动锁定”中的 UITableViewController 来构建一个选择界面,并且已经能够使复选标记正常工作,但我似乎无法弄清楚如何在再次调用 View 时让复选标记出现在先前选择的单元格上。

到目前为止,这是我选择复选标记的代码:

var lastSelectedIndexPath: NSIndexPath?

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.selectedDistance = distances[indexPath.row]
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    if indexPath.row != lastSelectedIndexPath?.row {
        if let lastSelectedIndexPath = lastSelectedIndexPath {
            let oldCell = tableView.cellForRowAtIndexPath(lastSelectedIndexPath)
            oldCell?.accessoryType = .None
        }

        let newCell = tableView.cellForRowAtIndexPath(indexPath)
        newCell?.accessoryType = .Checkmark

        lastSelectedIndexPath = indexPath
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("DataCell") as UITableViewCell
    cell.accessoryType = (lastSelectedIndexPath?.row == indexPath.row) ? .Checkmark : .None
    let distance = distances[indexPath.row]
    cell.textLabel?.text = distance.0
    cell.detailTextLabel?.text = "\(distance.1)"

    return cell

}

我想我可能必须将 lastSelectedIndexPath 存储在另一个文件中,但我不确定从这里去哪里。非常感谢任何帮助。

最佳答案

是的,您在这里回答了自己的问题。您需要以某种方式存储 lastSelectedIndexPath (即存储到您用于持久性的任何内容)。如果您还没有设置任何类型的数据库,一个简单的方法(阅读:不是最好的方法)是使用 NSUserDefaults 存储它。

关于swift - 在 Swift 中保存 UITableViewCell 复选标记选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30877677/

相关文章:

swift - 将您的类放在一个结构中是否是一种在 Swift 中为您的类命名空间的可接受方式?

ios - 如何在 Swift 中将可变参数(省略号)指定为可选参数?

ios - 将 UIApplicationDelegate 方法转换为 RxSwift Observables

iOS Parse Block 结果存储在 UILabel 中

ios - 在索引路径崩溃但不重新加载数据时插入行

ios - 如何更改 Collection View 单元格或按钮单击时的渐变?

swift - 从多重选择器行检索值时出现问题

ios - 快速在 TableView 的最后一个元素下方添加空间

ios - 点击另一个选项卡中的另一个按钮时如何更改按钮的图像

c# - Xamarin iOS ViewCellRenderer