在 UITableViewCell 上向右滑动

Swiping right on a UITableViewCell

所以我在网站上搜索了这个问题的答案,有一些不错的结果,但最近没有任何结果,因为 Xcode 7 不再处于测试阶段并且 swift 2.0 现在是标准.

我使用以下代码来实现 'swipe left' 功能会导致 UITableViewCell 发生某些事情 -

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){
    if editingStyle == UITableViewCellEditingStyle.Delete {
        // ...
    }
}

我知道这是 Apple 现在在他们的 API 中提供的东西,不需要使用外部 类。

我还了解到您可以使用本机代码自定义此次滑动所产生的操作:

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
    let more = UITableViewRowAction(style: .Normal, title: "More") { action, index in
    print("more button tapped")
}

是否有任何现代本机代码可以在 UITableViewCell 上定义 'right swipe'?

没有,目前还没有这样的原生API。

func tableView(_ tableView: UITableView,
               leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
    let closeAction = UIContextualAction(style: .normal, title:  "Close", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
        print("OK, marked as Closed")
        success(true)
    })
    closeAction.image = UIImage(named: "tick")
    closeAction.backgroundColor = .purple
    
    return UISwipeActionsConfiguration(actions: [closeAction])
}

func tableView(_ tableView: UITableView,
               trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
    let modifyAction = UIContextualAction(style: .normal, title:  "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
        print("Update action ...")
        success(true)
    })
    modifyAction.image = UIImage(named: "hammer")
    modifyAction.backgroundColor = .blue
    
    return UISwipeActionsConfiguration(actions: [modifyAction])
}

该功能在 iOS 11.0+ 和 Mac Catalyst 13.0+ 上可用。对于左侧的选项使用前导,右侧的选项使用尾随方法。

只需实施 UITableViewDelegate 方法和 return 您的 UISwipeActionsConfiguration object。您可以选择包含图片或仅包含文本作为按钮的标题。

func tableView(_ tableView: UITableView, 
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

func tableView(_ tableView: UITableView, 
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

确保在数据源委托中启用编辑,否则滑动选项将被禁用。

// True for enabling the editing mode
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}