我试图保存行的选定状态,以便当tableview加载所选行时会出现相应的复选标记。我在viewDidAppear中尝试过以下方法,但它无效。
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let checkMarkToDisplay = NSUserDefaults.standardUserDefaults().valueForKey("lastSelection") as! Int
lastSelection = NSIndexPath(forRow: checkMarkToDisplay, inSection: 0)
self.tableView.cellForRowAtIndexPath(lastSelection)?.accessoryType = .Checkmark
}
var lastSelection: NSIndexPath!
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if self.lastSelection != nil
{
self.tableView.cellForRowAtIndexPath(self.lastSelection)?.accessoryType = .None
}
if indexPath.row > 0
{
self.tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark
self.lastSelection = indexPath
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
NSUserDefaults.standardUserDefaults().setObject(indexPath.row, forKey: "lastSelection")
答案 0 :(得分:1)
请在cellForRowAtIndexPath中实现您的逻辑,并从viewDidAppear中删除您的复选标记代码。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let checkMarkToDisplay = NSUserDefaults.standardUserDefaults().valueForKey("lastSelection") as! Int
if checkMarkToDisplay == indexPath.row{
cell?.accessoryType = .Checkmark
}
else{
cell?.accessoryType = .None
}
}
答案 1 :(得分:0)
将其移至viewDidLoad()
lastSelection = NSIndexPath(forRow: checkMarkToDisplay, inSection: 0)
并删除此
self.tableView.cellForRowAtIndexPath(lastSelection)?.accessoryType = .Checkmark
然后将其添加到
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//create the cell
//then
cell.accessoryType = lastSelection == indexPath ? .Checkmark : .None
//other cell configuration
return cell
}