【问题标题】:ViewController + Storyboard setting up validation with controlTextDidChangeViewController + Storyboard 使用 controlTextDidChange 设置验证
【发布时间】: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


    【解决方案1】:

    我认为您关注的示例有点过时了。 试试……

        override func controlTextDidChange(_ notification: Notification) {
    

    ...作为NSTextFieldDelegate 中方法的函数定义。

    【讨论】:

    • 非常感谢。那成功了。我之前有覆盖,但方法签名略有不同,Xcode 在错误消息中并没有太大帮助。
    • 这在 Swift 5 中对我不起作用,但添加 @objc 解决了这个问题。这是我在使用 IB 设置文本字段的委托后最终编写的内容:@ objc func controlTextDidChange(_ obj: Notification) { print("text did change") }
    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 2019-03-18
    • 2015-10-05
    相关资源
    最近更新 更多