我希望在以任何方式编辑文本字段文本时调用函数。
我对swift和代码墙的新手并不能真正帮助我理解,而且我已经能够找到所有答案。
有人展示了自己按住Ctrl键点击文字字段,并按照“编辑确实开始”的名称显示已发送的操作。或类似的东西,但我只发出了一个叫做“行动”的行动。我需要澄清。
编辑:这适用于MacOS应用程序,UIKit无法正常工作。import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSTextFieldDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var msgBox: NSTextField!
@IBOutlet weak var keyBox: NSTextField!
@IBOutlet weak var encBtn: NSButton!
@IBOutlet weak var decBtn: NSButton!
override func controlTextDidChange(_ obj: Notification) {
//makeKey()
keyBox.stringValue = "test"
}
override func controlTextDidBeginEditing(_ obj: Notification) {
print("Did begin editing...")
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func makeKey() {
keyBox.stringValue = "test"
}
}
答案 0 :(得分:1)
在macOS上,您与iOS类似NSTextFieldDelegate
。
步骤是:
1)将NSTextField
实例拖放到窗口上。
2)将其代理人设置为NSViewController
:
3)让您的ViewController
(或任何其他管理类)实施NSTextFieldDelegate
,并实施任何所需的文本更改相关操作:
class ViewController: NSViewController, NSTextFieldDelegate {
// Occurs whenever there's any input in the field
override func controlTextDidChange(_ obj: Notification) {
let textField = obj.object as! NSTextField
print("Change occured. \(textField.stringValue)")
}
// Occurs whenever you input first symbol after focus is here
override func controlTextDidBeginEditing(_ obj: Notification) {
let textField = obj.object as! NSTextField
print("Did begin editing... \(textField.stringValue)")
}
// Occurs whenever you leave text field (focus lost)
override func controlTextDidEndEditing(_ obj: Notification) {
let textField = obj.object as! NSTextField
print("Ended editing... \(textField.stringValue)")
}
}