Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextView textDidChange event

Tags:

swift

I'm doing something similar to:

@IBOutlet var textView: NSTextView!

override func viewDidLoad() {
    super.viewDidLoad()

    textView.delegate = self
}

func textDidChange(notification: NSNotification) {

}

I did add "NSTextViewDelegate" at the very beginning.

I want to set the string value of a label if the text in the "textView" is changed.

The problem is that my program will just crash without any error message (breakpoint is at "fun textDidChange()......"). It will crash even if the func textDidChange is empty.

Am I doing anything wrong ?

Thanks

like image 990
Yoope Avatar asked Feb 03 '15 08:02

Yoope


1 Answers

Use this, Swift 3

class ViewController: NSViewController, NSTextViewDelegate {

  @IBOutlet var textView: NSTextView!

  override func viewDidLoad() {
    super.viewDidLoad()

    textView.delegate = self

  // NSTextViewDelegate conforms to NSTextDelegate
  func textDidChange(_ notification: Notification) {
    guard let textView = notification.object as? NSTextView else { return }
    print(textView.string)
  }
}

Remember

  • There is a _ in textDidChange(_ notification: Notification)
  • Swift 3 prefers Notification instead of NSNotification
  • Set a delegate textView.delegate = self
like image 73
onmyway133 Avatar answered Oct 15 '22 12:10

onmyway133