UITableViewRowAction与UISwipeActionsConfiguration的区别

15

这两个API似乎可以得到相同的结果。在什么情况下使用其中一个比另一个更好?


override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  let deleteAction = UITableViewRowAction(style: .destructive,
                                          title: "Delete") { (action, indexPath) in
    print("DELETE")
  }
  return [deleteAction]
}

:水平线标签,用于在网页中创建水平分隔线。
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  let DeleteAction = UIContextualAction(style: .destructive, title: "Delete", handler: { (action, view, success) in
      print("Delete")
  })
  DeleteAction.backgroundColor = .red
  return UISwipeActionsConfiguration(actions: [DeleteAction])
}
4个回答

11

它的基本功能相同,但自从 iOS 11 发布以来,滑动操作就可用了,并具有一些新功能:

  • 您可以为后滑和前滑设置操作
  • 您可以设置操作的图像action.image = UIImage(...)。如果有足够空间,它将显示图像和标题enter image description here

此外,您应该使用滑动操作,因为它们更受欢迎,在未来的更新中,UITableViewRowActions 将被弃用,如 UITableView 头注释所述:

请改用 -tableView:trailingSwipeActionsConfigurationForRowAtIndexPath: 方法,该方法将在将来的版本中弃用。


你能告诉我折旧通知在哪里吗? - Turnipdabeets
@Turnipdabeets,请为我跳转到第98行的UITableView定义及其注释。 - Robert Dresler

2
这是适用于我的代码:

这里是适用于我的代码

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

   // let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in
    let contextItem = UIContextualAction(style: .destructive, title: "") {  (contextualAction, view, boolValue) in
    // delete item at indexPath
       //if self.isfilterenabled == true {
         //   return
        //}


        if self.isfilterenabled == true {
            //entryFilter.filteredEntries[indexPath.row]
            self.entryFilter.filteredEntries.remove(at: indexPath.row)
        } else {
            self.data.remove(at: indexPath.row)
        }

        self.table.deleteRows(at: [indexPath], with: .fade)
        self.save()
    }



    //let share = UITableViewRowAction(style: .normal, title: "SavePDF") { (action, indexPath) in
        // share item at indexPath
    let contextItemSave = UIContextualAction(style: .normal, title: "") {  (contextualAction, view, boolValue) in





        let alert  = UIAlertController(title: "Done! ", message: "PDF has been saved " ,preferredStyle: .alert)

        let okAction = UIAlertAction(title: "OK ", style: .default, handler: nil)
        alert.addAction(okAction)

        alert.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        // exclude some activity types from the list (optional)
        //activityViewController.excludedActivityTypes = [ UIActivityTypeAirDrop, UIActivityTypePostToFacebook ]

        // present the view controller
        self.present(alert, animated: true, completion: nil)
        // present(alert, animated : true, completion : nil )

    }

   // share.backgroundColor = UIColor.blue

    contextItemSave.image = UIImage(named:"PDF.jpg")
    contextItem.image = UIImage(named:"delete.jpg")
    let swipeActions = UISwipeActionsConfiguration(actions: [contextItem,contextItemSave])

    return swipeActions
    //return [delete, share]
}`

1
我已经为UISwipeActionsConfiguration创建了一个扩展,如果您的图像大小存在问题,则可以使用该扩展。基本上,想法是从图像和文本创建一个属性字符串,并将其设置为标签,然后从该标签创建一个图像。并将其附加到UIContextualActionimage属性。
extension UISwipeActionsConfiguration {

    public static func makeTitledImage(
        image: UIImage?,
        title: String,
        textColor: UIColor = .white,
        font: UIFont = .systemFont(ofSize: 14),
        size: CGSize = .init(width: 50, height: 50)
    ) -> UIImage? {
        
        /// Create attributed string attachment with image
        let attachment = NSTextAttachment()
        attachment.image = image
        let imageString = NSAttributedString(attachment: attachment)
        
        /// Create attributed string with title
        let text = NSAttributedString(
            string: "\n\(title)",
            attributes: [
                .foregroundColor: textColor,
                .font: font
            ]
        )
        
        /// Merge two attributed strings
        let mergedText = NSMutableAttributedString()
        mergedText.append(imageString)
        mergedText.append(text)
        
        /// Create label and append that merged attributed string
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        label.textAlignment = .center
        label.numberOfLines = 2
        label.attributedText = mergedText
        
        /// Create image from that label
        let renderer = UIGraphicsImageRenderer(bounds: label.bounds)
        let image = renderer.image { rendererContext in
            label.layer.render(in: rendererContext.cgContext)
        }
        
        /// Convert it to UIImage and return
        if let cgImage = image.cgImage {
            return UIImage(cgImage: cgImage, scale: UIScreen.main.scale, orientation: .up)
        }
        
        return nil
    }
}

你可以像这样使用它;
public func tableView(
        _ tableView: UITableView,
        trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
    ) -> UISwipeActionsConfiguration? 
{
        let deleteAction = UIContextualAction(
            style: .normal,
            title:  nil,
            handler: { [weak self] (_, _, success: (Bool) -> Void) in
                success(true)
                print("Your action in here")
            }
        )
        
        deleteAction.image = UISwipeActionsConfiguration.makeTitledImage(
            image: UIImage(named: "delete_icon"),
            title: "Delete")
        )
        deleteAction.backgroundColor = .orange
        return UISwipeActionsConfiguration(actions: [deleteAction])
}

0

该方法(editActionsForRowAt)已被弃用。

现代方法使用不同的方法,即trailingSwipeActionsConfigurationForRowAt indexPath,在用户向左滑动时为行提供操作。

还有leadingSwipeActionsConfigurationForRowAt indexPath,可在用户向右滑动时提供操作。

以下是示例:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath)
    -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: nil) { (_, _, completionHandler) in
        // delete the item here
        completionHandler(true)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接