2
votes

There are five default menu items in the UIMenuController: Cut, Copy, Paste, Look Up, Share... I want to add one custom menuItem "Paste and Search" between menu "Paste" and "Look Up".

1
Are you will use for WebViewAbdelahad Darwish

1 Answers

2
votes

You can do this by disable System Menu and create your own menu using UIMenuController

Start to SubClass your view say UIWebView or UItextView , UIScrollView,..etc and ovveride this method override func canPerformAction(_ action: Selector, withSender sender: Any?) to disable system Menu item

Like that - UIWebView Example

import UIKit

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

Then Start to create your Own Menu, and implement its functions copy paste,...

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() {

    }
}