我检查了tableview列表中的多个项目后,我想从列表中删除它们并将它们添加到收藏夹列表中。
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//this is to make multiple selections in list
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark
//this gives me an array for rowsSelected
let rowsSelected = self.tableView.indexPathsForSelectedRows!.map{$0.row}
completeList.removeAtIndex(rowsSelected)
//tried this alternative - not sure what type "selection" is here
let selection = tableView.indexPathsForSelectedRows{
completeList.removeAtIndex(rowsSelected)
}
答案 0 :(得分:4)
为了能够从您的tableview中删除项目,您应该开始反向删除。这样就会出现您不会发生的问题。例如,如果您想从数组中删除说2,4,6 [ 1,2,3,4,5,6]你应该从6到2开始删除。为了更清楚你应该从最底层的单元格开始删除,然后索引不会超出范围。
示例:
if let indexPaths = tableView.indexPathsForSelectedRows {
//Sort the array so it doesn't cause a crash depending on your selection order.
let sortedPaths = indexPaths.sorted {$0.row > $1.row}
for indexPath in sortedPaths {
let count = array.count
var i = count-1
for i in stride(from: i, through: 0, by: -1) {
if(indexPath.row == i){
array.remove(at: i)
}
}
}
tableView.deleteRows(at: sortedPaths, with: .automatic)
}
答案 1 :(得分:1)
Swift 3
离开EmirC的答案我遇到了困难,因为它删除了indexPaths数组中较早的行,然后出现了不连续性并最终崩溃,所以我想出了这个解决问题的解决方案。 if let indexPaths = tableView.indexPathsForSelectedRows {
let sortedArray = indexPaths.sorted {$0.row < $1.row}
for i in (0...sortedArray.count-1).reversed() {
Tasks.remove(at: sortedArray[i].row)
}
tableView.deleteRows(at: sortedArray, with: .automatic)
}