How to add custom action to text editing menu in iOS?

I need to add a custom action to the edit menu that appears when the user selects some text in a UITextView in iOS. How can I do it? (Swift code is preferred).

+5
source share
1 answer
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 a 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

+10
source

All Articles