如何在UIMenuController的指定位置添加自定义menuItem?

时间:2018-05-09 02:58:24

标签: ios swift uimenucontroller

UIMenuController中有五个默认菜单项:剪切,复制,粘贴,查找,共享......我想添加一个自定义menuItem"粘贴和搜索"菜单"粘贴"和"查找"。

1 个答案:

答案 0 :(得分:1)

您可以通过禁用系统菜单并使用UIMenuController

创建自己的菜单来执行此操作

开始SubClass您的视图说UIWebViewUItextViewUIScrollView,..等,并使用此方法override func canPerformAction(_ action: Selector, withSender sender: Any?)以禁用系统菜单项

像那样 - UIWebView示例

import UIKit

class CustomWebView: UIWebView {
   override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
          return false  // Disable Menu system
       }
 }

然后开始创建自己的菜单,并实现其功能复制粘贴,...

class  ViewController: UIViewController{

    @IBOutlet var webView: CustomWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.webView.loadHTMLString("<p>Hello, world!</p>", baseURL: nil)
        enableCustomMenu()
    }



    func enableCustomMenu() {
        let cut = UIMenuItem(title: "Cut", action: #selector(runCut))
        let copy = UIMenuItem(title: "Copy", action: #selector(runCopy))
        let paste = UIMenuItem(title: "Paste", action: #selector(runPaste))
        let pasteSearch = UIMenuItem(title: "Paste and Search", action: #selector(runPasteSearch))
        let look = UIMenuItem(title: "Look Up", action: #selector(runLook))

   //  ----> here Arrange as you can
        UIMenuController.shared.menuItems = [cut,copy,paste,pasteSearch,look]
    }

    func disableCustomMenu() {
        UIMenuController.shared.menuItems = nil
    }

    @objc func runCut() {
    }
    @objc func runCopy() {
        let text = webView.stringByEvaluatingJavaScript(from: "window.getSelection().toString();")
        print(text ?? "")
    }
    @objc func runPaste() {

    }
    @objc func runPasteSearch() {

    }
    @objc func runLook() {

    }
}