Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen for changes to NSTextView with NSTextViewDelegate & textViewDidChange not working

I want a function to fire every time the user makes a change to my NSTextView. I got this to work in an iOS app and am now trying to make it work in an OS X app. I created an outlet for my NSTextView and wrote the following Swift code:

import Cocoa

class ViewController: NSViewController, NSTextViewDelegate {

    @IBOutlet var textViewOutlet: NSTextView!

    func textViewDidChange(textView: NSTextView) {
        print("Text view changed!")
    }
}

I don't get any errors but my statement doesn't print.

like image 772
user1822824 Avatar asked Dec 01 '22 13:12

user1822824


2 Answers

It should be textDidChange(notification:). Try like this:

func textDidChange(_ notification: Notification) {
    guard let textView = notification.object as? NSTextView else { return }
    print(textView.string)
}
like image 199
Leo Dabus Avatar answered May 16 '23 06:05

Leo Dabus


This should be why there is no delegate assignment.

TextViewOutlet.delegate = self;

And the method actually looks like this. Notice the parameters

func textDidChange(_ notification: Notification) {

}
like image 27
Simon Avatar answered May 16 '23 07:05

Simon