【问题标题】:Set UIContextMenu for WKWebView links为 WKWebView 链接设置 UIContextMenu
【发布时间】:2020-10-09 03:45:49
【问题描述】:

我们如何为 WKWebView 中的链接设置自定义上下文菜单?

您可以通过执行以下操作在项目上设置上下文菜单:

    let interaction = UIContextMenuInteraction(delegate: self)
    someItem.addInteraction(interaction)

并添加 UIContextMenuInteractionDelegate 委托:

 func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
        let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { (_) -> UIMenu? in
            let shareAction = UIAction(title: "Send to Friend", image: UIImage(systemName: "square.and.arrow.up")) { _ in
                // Pressed
            }
            let menu = UIMenu(title: "", children: [shareAction])
            return menu
        }
        return configuration
    }

当用户按住 WKWebView 中的链接时,如何使用自定义上下文菜单?

【问题讨论】:

    标签: swift webkit wkwebview


    【解决方案1】:

    您应该为您的WKWebView 实现contextMenuConfigurationForElement UI 委托方法,例如:

    override func viewDidLoad() {
        ...
        webView?.uiDelegate = self
    }
    
    extension ViewController : WKUIDelegate {
        
        func webView(_ webView: WKWebView, contextMenuConfigurationForElement elementInfo: WKContextMenuElementInfo, completionHandler: @escaping (UIContextMenuConfiguration?) -> Void) {
            let share = UIAction(title: "Send to Friend") { _ in print("Send to Friend") }
            let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
              UIMenu(title: "Actions", children: [share])
            }
            completionHandler(configuration)
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多