我需要在 iOS 的 UITextView 中添加一个自定义操作到编辑菜单中,该菜单在用户选择某些文本时弹出。
我该如何做呢?
我需要在 iOS 的 UITextView 中添加一个自定义操作到编辑菜单中,该菜单在用户选择某些文本时弹出。
我该如何做呢?
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
可以执行任何您想要的操作。
注意:这是在Swift 3中实现的 (如果需要Swift 2.3版本,请询问)
希望这可以帮到您!如果您有任何问题,请随时问!:D
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)
}
}
}
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
}
}
我还制作了一个YouTube视频,在这里解释了这个问题。