OGeek|极客世界-中国程序员成长平台

标题: ios - 在条件和 UI 澄清的情况下删除 tableView 行 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:05
标题: ios - 在条件和 UI 澄清的情况下删除 tableView 行

我需要一种允许用户删除 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 条目?

任何帮助将不胜感激!谢谢。



Best Answer-推荐答案


试试这个以防止其他单元格编辑:

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

关于ios - 在条件和 UI 澄清的情况下删除 tableView 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29708861/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4