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?
Asked
Active
Viewed 1.0k times
12

LinusGeffarth
- 27,197
- 29
- 120
- 174

TomLisankie
- 3,785
- 7
- 28
- 32
3 Answers
22
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

Ike10
- 1,585
- 12
- 14
-
Thanks, this was very helpful. Is there any way to: 1. have my custom action appear only when text is selected 2. move up to the front of the list of actions (aka before the "cut" action) 3. get the text that was selected – TomLisankie Jun 17 '16 at 07:47
-
After some research, I am unsure that 1 and 2 are possible. 2 may be possible, but it would require creating your own text selection menu from what is most likely private apple APIS (not allowed). As for 3, I have edited my example to print the selected text to the console. @Shaken_Earth – Ike10 Jun 17 '16 at 22:02
4
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)
}
}
}

Greg432
- 530
- 4
- 25
0
Here is how you create a custom edit menu in 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
}
}
I have also made a youtube video explaining this here

Aryaa Sk
- 81
- 1
- 5