Swift - UITableView didSelectRowAtIndexPath & didDeselectRowAtIndexPath Add & Remove indexPath IDs

末鹿安然 提交于 2019-11-30 05:30:40

You could do this pretty simply by adding a 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)
        }
    }
}
Aks

For Swift 3.0, use

override  func tableView(_ tableView: UITableView, didSelectRowAt
 indexPath: IndexPath){
     //your code...  
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!