ios Swift - UITableView didSelectRowAtIndexPath & didDeselectRowAtIndexPath 添加和删除 indexPath ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26740538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - UITableView didSelectRowAtIndexPath & didDeselectRowAtIndexPath Add & Remove indexPath IDs
提问by Bogdan Bogdanov
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
如何在“数组或字符串或其他...”中添加项目 ID?例如,当您选择第 0、1、4、5 行时,您在“数组或字符串中”添加了不同的项目 ID,然后当我想取消选择它们时,如何从取消选择的 indexPath.row 中取消选择确切的项目 ID 并找到它“在数组或字符串或其他东西中......”并删除它?如果您在评论中有问题,我会为我的英语蹩脚感到抱歉,如果可以,我会解释
回答by Nate Cook
You could do this pretty simply by adding a Dictionary
property to your table view controller:
您可以通过向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)
}
}
}
回答by Aks
For Swift 3.0, use
对于 Swift 3.0,请使用
override func tableView(_ tableView: UITableView, didSelectRowAt
indexPath: IndexPath){
//your code...
}