Swift – UITableView didSelectRowAtIndexPath&didDeselectRowAtIndexPath添加和删除indexPath ID

这是代码:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedItem = items.objectAtIndex(indexPath.row) as String let itemId = selectedItem.componentsSeparatedByString("$%^") //itemId[1] - Item Id } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { let selectedItem = items.objectAtIndex(indexPath.row) as String let itemId = selectedItem.componentsSeparatedByString("$%^") //itemId[1] - Item Id } 

如何添加项目ID“在数组或string或其他东西…”? 当你select行0,1,4,5例如你有不同的项目ID添加“在数组或string”,然后当我想取消select如何从取消select的indexPath.row中取消select确切的项目ID它“在数组或string或其他东西…”并删除它? 对不起,如果你有问题在评论中提问,我会解释,如果我可以

你可以简单地通过添加一个Dictionary属性到你的表视图控制器来做到这一点:

 class ViewController : UITableViewController { var selectedItems: [String: Bool] = [:] // ... func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedItem = items.objectAtIndex(indexPath.row) as String let itemId = selectedItem.componentsSeparatedByString("$%^") // add to self.selectedItems selectedItems[itemId[1]] = true } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { let selectedItem = items.objectAtIndex(indexPath.row) as String let itemId = selectedItem.componentsSeparatedByString("$%^") // remove from self.selectedItems selectedItems[itemId[1]] = nil } // can access the items as self.selectedItems.keys func doSomething() { for item in selectedItems.keys { println(item) } } } 

对于Swift 3.0,使用

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ //your code... }