简体   繁体   中英

NSTextView textDidChange event

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

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

See this answer: textDidChange vs controlTextDidChange

In short, use controlTextDidChange: instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM