且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-14 15:49:16

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 可以执行所需的任何操作。

This is an example of text selection menu item that changes the text in a UITextView to red. changeToRedFunc can perform any action you want.

注意:这是在Swift 3中
(如果需要,请在Swift 2.3中询问)

Note: This is in Swift 3 (ask if you want it in Swift 2.3)

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

Hope this helps! If you have any questions feel free to ask! :D