如何限制只对某些用户删除 TableView 中的行?

How to restrict deleting rows in TableView only to certain users?

我的问题如下。我创建了一个应用程序,允许用户将 posts 添加到 TableViewController 中的行。它还允许他们通过检查当前用户是否与创建 post 的用户具有相同的 ID 来仅删除具有 UITableViewCellEditingStyle 的 post。不幸的是,这种编辑单元格的方式也允许尝试删除其他用户 posts。我想让删除按钮仅在用户滑动 post 时出现。我附上an image of the button 我一直在讲。

只需在表视图的委托中检查匹配的用户 ID editingStyleForRowAtIndexPath,如果用户无效则返回 UITableViewCellEditingStyle.None

Reference for editingStyleForRowAtIndexPath

你可以这样做:

如果您没有自定义 class UITableViewCell:

override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
    if owner[indexPath.row] == me {
        return .Delete
    }
    else {
        return .None
    }
 }

如果你有自定义 class 的 UITableViewCell 那么这个:

override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
    if (tableView.cellForRowAtIndexPath(indexPath) as! YourTableViewCell).owner == me {
        return .Delete
    }
    else {
        return .None
    }
}

你也可以试试这个,记得给单元格设置默认的editingStyle

    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return owner[indexPath.row] == me
    }