我想以任何方式编辑文本字段文本时调用函数。
我是swift和代码墙的新手并没有真正帮助我理解,而这一切我都能找到答案。
有人用ctrl点击文本字段并显示一个名为'editing did start'的发送动作或类似的东西,但我只发送了一个名为'action'的动作。我需要澄清一下。
编辑:这是一个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"
}
}
在macOS上,你有类似于iOS,NSTextFieldDelegate
。
步骤是:
1)将n-drop-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)")
}
}