我正在尝试使用类似于“设置”->“常规”->“自动锁定”中的 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/