如何在iOS的文本选择编辑菜单中添加自定义操作? [英] How do I add a custom action to the text selection edit menu in iOS?
本文介绍了如何在iOS的文本选择编辑菜单中添加自定义操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要向用户在iOS的UITextView中选择一些文本时弹出的编辑菜单中添加自定义操作。
我该怎么做?
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?
推荐答案
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
这篇关于如何在iOS的文本选择编辑菜单中添加自定义操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文