gpt4 book ai didi

macos - 如何实时检查 NSTextField - Swift OS X

转载 作者:行者123 更新时间:2023-12-02 00:00:34 25 4
gpt4 key购买 nike

我目前正在制作一个用 Swift 编写的 OS X 应用程序。我想要做的是,当用户在 NSTextField 中输入文本时,我想运行一个函数来检查该值并将其添加到标签中。我该如何快速做到这一点?

最佳答案

  1. 使 ViewController 符合协议(protocol) NSTextDelegate
  2. ViewController 指定为 TextField 的委托(delegate)。
  3. 实现 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
    }
    }

在 View Controller 中:

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
}
}
}
}

关于macos - 如何实时检查 NSTextField - Swift OS X,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34694522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com