我需要一种允许用户删除tableView行的方法,只有在满足条件的情况下(如果source ==" MyApp")。我在下面提供了一个有效的例子。
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let source = objectSample[indexPath.row].source.name
if source == "MyApp"{
if (editingStyle == UITableViewCellEditingStyle.Delete) {
let UUIDtoDelete = objectSample[indexPath.row].UUID
deleteUUIDobject(UUIDtoDelete)
objectSample.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
println("Deleted")
}
}
else {
println("Not allowed to delete")
}
}
生成的UI对用户来说有点混乱,因为它会使所有行都带有红色滑动删除按钮,无论他/她是否可以实际删除该行。因此,如果条件不满足,我尝试将删除按钮设置为灰色:
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
let source = objectSample[indexPath.row].source.name
println(source)
if source == "MyApp"{
var deleteButtonRed = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action, indexPath) in
println("To delete is OK, set color red")
})
deleteButtonRed.backgroundColor = UIColor.redColor()
return [deleteButtonRed]
}
else{
var deleteButtonGray = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action, indexPath) in
println("To delete is NOT OK, ret color gray")
})
deleteButtonGray.backgroundColor = UIColor.grayColor()
return [deleteButtonGray]
}
return ["Will Never Happen"]
}
我的问题是这些方法无法协同工作。出于某种原因,如果我应用方法editActionsForRowAtIndexPath,则永远不会评估commitEditingStyle。即使source ==" MyApp",该行也不会被删除。我如何将两者结合在一起?
或者有更好的方法来显示用户可以/不能删除哪些tableView条目?
非常感谢任何帮助!谢谢。
答案 0 :(得分:2)
尝试此操作以防止编辑其他单元格:
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return source == "MyApp"
}
或者这使得其他单元格可以编辑,但没有删除控件:
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if source == "MyApp" {
return UITableViewCellEditingStyle.Delete
} else {
return UITableViewCellEditingStyle.None
}
}