ios swift:Tableview“un”-checkmark cell
在cellForRowAtIndexPath
方法中,我这样做,当我知道,有数据我可以勾选:
if (self.selectedLessonObject != nil){ if(lessons["name"] as String == selectedLessonObject["name"] as String){ cell.accessoryType = .Checkmark } }
在didSelectRowAtIndexPath
我执行:
// update the checkmark for the current row let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.accessoryType = .Checkmark
我还搞不清楚如何在select新的单元格之前取消select旧的单元格?
如何将选定的行保存在cellForRowAtIndexPath
并在didSelectRowAtIndexPath
访问它以取消select它?
谢谢!!
编辑:
当我尝试这个:
var lastSelectedRow: NSIndexPath? = nil
在cellForRowAtIndexPath
if (self.selectedLessonObject != nil){ if(lessons.objectId == selectedLessonObject.objectId){ cell.accessoryType = .Checkmark lastSelectedRow = tableView.indexPathForSelectedRow() }else{ cell.accessoryType = .None } } println("selected: \(lastSelectedRow)")
我得到一个零输出。
在didSelectRowAtIndexPath
我想到了这个:
// Other row is selected - need to deselect it // catch the previous selected row var oldcell = tableView.cellForRowAtIndexPath(lastSelectedRow!) oldcell?.accessoryType = .None
但我无法捕捉从当前行从cellForRowAtIndexPath
didSelectRowAtIndexPath
如果您在didSelectRowAtIndexPath
select新行,请检查新属性是否为空,如果是,则通过调用
if let last = lastSelectedRow { let oldSelectedCell = tableView.cellForRowAtIndexPath(last) oldSelectedCell.accessoryType = .None } lastSelectedRow = indexPath let cell = tableView.cellForRowAtIndexPath(indexPath) cell.accessoryType = .Checkmark
在cellForRowAtIndexPath
检查新属性是否为空,等于indexPath,否则取消勾选:
if let last = lastSelectedRow { if (self.selectedLessonObject != nil){ if(lessons.objectId == selectedLessonObject.objectId && last == indexPath){ cell.accessoryType = .Checkmark }else{ cell.accessoryType = .None } } else{ cell.accessoryType = .None } } else{ if (self.selectedLessonObject != nil){ if(lessons.objectId == selectedLessonObject.objectId){ cell.accessoryType = .Checkmark lastSelectedRow = indexPath }else{ cell.accessoryType = .None } } }
您可以保存indexPath或所选单元格的行。 或者你可以试着从:
tableview.indexPathForSelectedRow()
lastSelectedRow = indexPath let cell = tableView.cellForRowAtIndexPath(indexPath) cell!.accessoryType = .Checkmark if selected.count > 0{ if selected.containsObject(lastSelectedRow!.row){ if cell!.accessoryType == .Checkmark{ cell!.accessoryType = .None selected.removeObject(lastSelectedRow!.row) }else{ cell!.accessoryType = .Checkmark } }else{ selected.addObject(lastSelectedRow!.row) } }else{ selected.addObject(lastSelectedRow!.row) }