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

房东的猫 提交于 2021-01-16 08:30:53

问题


I need to add a custom action to the edit menu that pops up when a user selects some text in a UITextView in iOS.
How do I do this?


回答1:


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)
      }
   }
}

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.

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

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




回答2:


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)
       }
    }
}


来源:https://stackoverflow.com/questions/37870889/how-do-i-add-a-custom-action-to-the-text-selection-edit-menu-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!