Search code examples
swiftmacoscocoanstextfield

How to update the value of a NSTextField object while the user is editing it?


I’m currently creating a text entry that allows the user to enter some texts and use it as some kind of title. Then I had this idea of making a preview for this text entry, but I don’t know how to update the preview content as the user is editing the text entry.

For example, once the user type something into the text entry, the preview label automatically and immediately respond to display the text written by the user. (the user doesn’t have to do anything) I’ve seen a lot of tutorials online about “how to live check a NSTextField?”, but I’ve tried their ways, it didn’t work.

I’m using Xcode 10.0 with Swift 4.2, is there any way to achieve this?


Solution

  • I figured out how to do this:

    extension ViewController: NSTextFieldDelegate {
        func controlTextDidChange(_ obj: Notification) {
            guard let textView = obj.object as? NSTextField else {
                return
            }
            // codes
        }
    }