Swift - UITableView madeSelectRowAtIndexPath & didDeselectRowAtIndexPath Add and remove index ids

This is the code:

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 } 

How to add Item Id "to Array or String or something else ..."? When you select strings 0,1,4,5, for example, you have different element identifiers added β€œin an array or in String”, and then when I want to cancel them, how to cancel the desired element identifier from indexPath.row, which not selected and it finds "in an array or in String or something else ..." and deleted it? Sorry for my broken English if you have any questions asked in the comments and I will explain if I can

+6
source share
2 answers

You can do this quite simply by adding the Dictionary property to your table view controller:

 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) } } } 
+21
source

For Swift 3.0 use

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

Source: https://habr.com/ru/post/977719/


All Articles