如何实时检查NSTextField-Swift OS X [英] How to live check a NSTextField - Swift OS X
本文介绍了如何实时检查NSTextField-Swift OS X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在制作用Swift编写的OS X应用程序.我想做的是,当用户在NSTextField
中输入文本时,我想运行一个检查值并将其添加到Label的函数.我将如何迅速做到这一点?
I am currently making an OS X application written in Swift. What I want to do is when the user enters text in a NSTextField
, I want to run a function that checks the value and adds it to a Label. How would I do this in swift?
推荐答案
- 使
ViewController
符合协议NSTextDelegate
. - 将
ViewController
指派为TextField
的代表. -
实施
controlTextDidChange
方法.
- Conforms
ViewController
to protocolNSTextDelegate
. - Assign
ViewController
as Delegate forTextField
. Implement
controlTextDidChange
method.
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中:
in 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
}
}
}
}
这篇关于如何实时检查NSTextField-Swift OS X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文