为 WKWebView 链接设置 UIContextMenu
Set UIContextMenu for WKWebView links
我们如何在 WKWebView 中为 link 设置自定义上下文菜单?
您可以通过执行以下操作在项目上设置上下文菜单:
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 中按住 link 时如何使用自定义上下文菜单?
您应该为您的 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)
}
}
我们如何在 WKWebView 中为 link 设置自定义上下文菜单?
您可以通过执行以下操作在项目上设置上下文菜单:
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 中按住 link 时如何使用自定义上下文菜单?
您应该为您的 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)
}
}