我目前正在制作一个用 Swift编写的OS X应用程序.我想要做的是当用户在NSTextField中输入文本时,我想运行一个检查值并将其添加到Label的函数.我怎么能在swift中做到这一点? 使ViewControlle
>将ViewController指定为TextField的委托.
>实现controlTextDidChange方法.
import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSTextFieldDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var textField: NSTextField! @IBOutlet weak var label: NSTextField! func applicationDidFinishLaunching(aNotification: NSNotification) { textField.delegate = self } override func controlTextDidChange(notification: NSNotification) { let object = notification.object as! NSTextField self.label.stringValue = object.stringValue } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
在ViewController中:
import Cocoa class ViewController: NSViewController, NSTextDelegate { @IBOutlet weak var label: NSTextField! @IBOutlet weak var label2: NSTextField! @IBOutlet weak var textField: NSTextField! @IBOutlet weak var textField2: NSTextField! override func viewDidLoad() { super.viewDidLoad() } override func controlTextDidChange(notification: NSNotification) { if let txtFld = notification.object as? NSTextField { switch txtFld.tag { case 201: self.label.stringValue = txtFld.stringValue case 202: self.label2.stringValue = txtFld.stringValue default: break } } } }