Text change notification for an NSTextField

前端 未结 5 678
不知归路
不知归路 2020-12-08 03:58

I would like to use the code from the answer to this question: How to observe the value of an NSTextField on an NSTextField in order to observe changes on the string stored

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 04:36

    Xcode 9.2. with Swift 4.0.3.

    The NSTextField must be connected via interface builder for this implementation to work.

    import Cocoa
    
    @objc public class MyWindowController: NSWindowController, NSTextFieldDelegate {
    
    @IBOutlet weak var myTextField: NSTextField!
    
    // MARK: - ViewController lifecycle -
    
    override public func windowDidLoad() {
        super.windowDidLoad()
        myTextField.delegate = self
    }
    
    // MARK: - NSTextFieldDelegate -
    
    public override func controlTextDidChange(_ obj: Notification) {
        // check the identifier to be sure you have the correct textfield if more are used 
        if let textField = obj.object as? NSTextField, self.myTextField.identifier == textField.identifier {
            print("\n\nMy own textField = \(self.myTextField)\nNotification textfield = \(textField)")
            print("\nChanged text = \(textField.stringValue)\n")
        }
    }
    

    }

    Console output:

    My own textField = Optional()
    Notification textfield = 
    
    Changed text = asdasdasddsada
    

提交回复
热议问题