是否可以通过编程方式禁用commitEditingStyle?

Hen*_*els 5 action edit tableview swift

在我的tableview中,我只希望某些单元格能够根据条件向左拖动某些选项.其他单元格的行为应该像commitEditingStyle禁用一样.这可能吗?

使用下面的代码,我可以在满足条件时添加操作,但其他单元格仍然可以获得默认的"删除"操作.如何摆脱删除操作?

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {

    let object = items[indexPath.row]
    if object.name == "name" {

        // someAction
        var addAction = UITableViewRowAction(style: .Default, title: "+") { (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in
        }
        return [addAction]
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

使用下面的代码,我设法启用和禁用操作.但只有Delete按钮.

override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {

    let object = items[indexPath.row]
    if object.name == "joyce" {
        return UITableViewCellEditingStyle.Delete
    } else {
        return UITableViewCellEditingStyle.None
    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*rik 5

您需要一种基于数据模型确定可编辑状态的方法.例如:

class Message
{
    var subject : String
    var title : String
    var isEditable : Bool

    init(subject: String, title: String)
    {
        self.subject = subject
        self.title = title
        self.isEditable = true
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个,您可以轻松处理tableView:canEditRowAtIndexPath:委托方法.您的视图控制器应如下所示:

class ViewController : UIViewController, UITableViewDataSource, UITableViewDelegate
{
    var tableView : UITableView!
    var messages : [Message]

    // MARK: - UITableView Delegate

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.messages.count
    }

    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
    {
        let message = self.messages[indexPath.row]
        return message.isEditable
    }
}
Run Code Online (Sandbox Code Playgroud)

在一些更复杂的例子中,它可能是计算属性,但整体概念是相同的.


Phi*_*lls 2

听起来你正在寻找optional func tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool

来自苹果文档:

该方法允许数据源排除个别行,使其不被视为可编辑。可编辑行在其单元格中显示插入或删除控件。如果未实现此方法,则假定所有行都是可编辑的。