【发布时间】:2017-01-03 13:52:16
【问题描述】:
尝试在一个新的(非常小的)Swift Mac 应用程序中为几个文本字段设置验证。在 SO 上的各种其他主题和其他一些示例之后,我仍然无法让 controlTextDidChange 传播(到我的 ViewController)。
例如:How to live check a NSTextField - Swift OS X
我已经阅读了至少十几个基本相同概念的变体。由于所有公认的答案似乎都不起作用,我只是对一些在大多数平台上通常相当简单的任务感到越来越困惑。
我已经实现了 controlTextDidChange,只需要调用 NSLog 来让我知道我是否得到任何东西。
AppDelegate 应该是响应者链的一部分,并且最终应该处理 controlTextDidChange,但我在那里也看不到任何东西。
使用当前的 Xcode 我开始了一个新项目。 Cocoa 应用、Swift、Storyboard 等等。
据我所知,下面的孤立示例应该可以工作。在我的实际应用程序中,我尝试了一些将 ViewController 插入响应者链的方法。我发现的一些答案表明它并不总是存在。我还尝试在代码 theTextField.delegate = self
中手动添加 ViewController 作为委托我所做的一切似乎都没有改变文本以触发任何事件。
知道为什么我在设置这个代表团时遇到这么多麻烦吗?
我的单个文本字段示例应用程序
故事板非常简单:
AppDelegate
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSTextFieldDelegate, NSTextDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func controlTextDidChange(notification: NSNotification) {
let object = notification.object as! NSTextField
NSLog("AppDelegate::controlTextDidChange")
NSLog("field contains: \(object.stringValue)")
}
}
视图控制器
import Cocoa
class ViewController: NSViewController, NSTextFieldDelegate, NSTextDelegate {
@IBOutlet var theTextField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func controlTextDidChange(notification: NSNotification) {
let object = notification.object as! NSTextField
NSLog("ViewController::controlTextDidChange")
NSLog("field contains: \(object.stringValue)")
}
}
【问题讨论】:
标签: swift xcode cocoa swift3 appkit