如何将自定义操作添加到 iOS 中的文本选择编辑菜单?

How do I add a custom action to the text selection edit menu in iOS?

我需要向当用户在 iOS 的 UITextView 中选择某些文本时弹出的编辑菜单添加自定义操作。
我该怎么做?

class ViewController: UIViewController, UITextViewDelegate {

   @IBOutlet weak var textView: UITextView!

   override func viewDidLoad() {
      super.viewDidLoad()

      addCustomMenu()
   }

   func addCustomMenu() {
      let printToConsole = UIMenuItem(title: "Print To Console", action: #selector(printToConsole))
      UIMenuController.shared().menuItems = [printToConsole]
   }

   func printToConsole() {
      if let range = textView.selectedTextRange, let selectedText = textView.text(in: range) {
         print(selectedText)
      }
   }
}

这是将 UITextView 中的文本更改为红色的文本选择菜单项示例。 changeToRedFunc 可以执行您想要的任何操作。

注意:这是在Swift3 (在Swift2.3中询问是否需要)

希望对您有所帮助!如果你有任何问题随时问! :D

SWIFT 5

class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

         addCustomMenu()
    }


    func addCustomMenu() {
       //Xcode doesn't like printToConsole being a var and a function call
       let printToConsole = UIMenuItem(title: "Print To Console", action: #selector(printToConsole2))

        UIMenuController.shared.menuItems = [printToConsole]
    }

    @objc func printToConsole2() {
       if let range = textView.selectedTextRange, let selectedText = textView.text(in: range) {
          print(selectedText)
       }
    }
}

以下是在 swift 5 中创建自定义编辑菜单的方法:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var textfield: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let changeBackground = UIMenuItem(title: "Change Background Colour", action: #selector(changeBackgroundColour))
        UIMenuController.shared.menuItems = [changeBackground] //will add it to everything that has
    
    }

    @objc func changeBackgroundColour()
    {
        self.view.backgroundColor = .cyan //just makes the background colour cyan
    }

}

我还制作了一个 youtube 视频来解释这个 here