onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
678 stars 33 forks source link

How to handle NSTextField change in macOS #438

Open onmyway133 opened 5 years ago

onmyway133 commented 5 years ago

Storyboard

In Storyboard, NSTextField has an Action option that specify whether Send onSend on Enter only` should be the default behaviour.

textfield

Code

In code, NSTextFieldDelegate notifies whenever text field value changes, and target action notifies when Enter key is pressed

import Cocoa

class ViewController: NSViewController, NSTextFieldDelegate {

    @IBOutlet weak var textField: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.delegate = self
    }

    func controlTextDidChange(_ obj: Notification) {
        let textField = obj.object as! NSTextField
        print(textField.stringValue)
    }
}

Use EasyClosure

If we use EasyClosure then this is easy

let textField: NSTextField = 

textField.on.action { string in
    print("User has pressed enter \(string)"
}

textField.on.change { string in
    print("Text field value has changed")
}
noblesilence commented 3 years ago

I tried this code and viewDidLoad gets called but controlTextDidChange does not. Any idea what I am doing wrong? I initiatate the ViewController in code:

NSTabViewItem *tabViewItem = [[NSTabViewItem alloc]
       initWithIdentifier:@"time"];
    [tabViewItem setLabel:@"Time"];
    [tabView tabViewItem];

ViewController *viewController = [[ViewController alloc]
       initWithNibName:@"tabView" bundle:nil];
[tabViewItem setView:[viewController view]];