我正在用 OrderDetailsArray
填充我的 tableView
。然后在 DidSelect
上,我将值添加到 reorderArray
。
如何在点击 DidDeSelect
时从数组中删除值?
我的 tableView 委托(delegate)函数:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let object = orderDetailsArray.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
let storeID = UserDefaults.standard.value(forKey: DefaultsKey.storeID.rawValue) as! Int
let barcode = object["barcode"] as! String
let mrp = object["mrp"] as! String
let productDiscount = object["product_discount"] as! String
reorderDictionary.setObject((storeID), forKey: "store_id" as NSCopying)
reorderDictionary.setObject((barcode), forKey: "barcode" as NSCopying)
reorderDictionary.setObject((mrp), forKey: "mrp" as NSCopying)
reorderDictionary.setObject((productDiscount), forKey: "product_discount" as NSCopying)
reorderArray.add(reorderDictionary)
let cell = tableView.cellForRow(at: indexPath) as! OrderHistoryProductDetailsTableViewCell
cell.contentView.backgroundColor = UIColor.red
print(reorderArray)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! OrderHistoryProductDetailsTableViewCell
let object = reorderArray.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
reorderArray.remove(object)
cell.contentView.backgroundColor = UIColor.clear
print(reorderArray)
}
reorderArray 是 NSMutableArray()
最佳答案
你不应该在 Swift 中使用诸如 NSMutableArray
或 NSDictionary
之类的基础类,除非你有充分的理由,但简单的答案是你可以使用 remove
从 NSMutableArray
中删除对象的实例,您可以轻松地从索引路径中找到相关对象:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! OrderHistoryProductDetailsTableViewCell
let object = orderDetailsArray.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
reorderArray.add(object)
cell.contentView.backgroundColor = UIColor.red
print(reorderArray)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let object = orderDetailsArray.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
reorderArray.remove(object)
let cell = tableView.cellForRow(at: indexPath) as! OrderHistoryProductDetailsTableViewCell
cell.contentView.backgroundColor = UIColor.clear
print(reorderArray)
}
关于ios - 如何在 Did DeSelect 中删除字典数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44045550/