Swift - UITableView didSelectRowAtIndexPath & didDeselectRowAtIndexPath Add & Remove indexPath IDs

橙三吉。 提交于 2019-11-29 03:07:49

问题


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 "in Array or in String or something else..."? When you select rows 0,1,4,5 for example you have different Item Ids added "in Array or in String" and then when I want to deselect them how to deselect exact Item Id from the indexPath.row that is deselected and find it "in Array or in String or something else..." and deleted it ? Sorry for my broken english if you have a questions ask in comments and I will explain if I can


回答1:


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)
        }
    }
}



回答2:


For Swift 3.0, use

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


来源:https://stackoverflow.com/questions/26740538/swift-uitableview-didselectrowatindexpath-diddeselectrowatindexpath-add-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!