I'm currently coding a text editor in swift and I'm having trouble with inserting a new line ("\n") when pressing enter/return.
By now, when pressing enter, the textField inserts a new line but ends editing with no reason.
Here is my function which will only be called when enter is pressed.
@IBAction func textFieldAction(_ sender: NSTextField) {
self.textField?.stringValue.append("\n")
self.textField?.selectAll(nil)
}
If there is more of my code needed the whole file can be found here: https://github.com/notalent/manuscript-mac/blob/master/Manuscript/Document.swift
I think the correct answer is "don't use NSTextField
; use NSTextView". NSTextField
wasn't designed to do what you're trying to do. The Cocoa Text Architecture Guide has a bunch of information on both NSTextField
and NSTextView
. See also this question here on SO.
But, if you insist on using NSTextField
, you can implement the delegate method control:textView:doCommandBySelector:
to provide special handling of return/enter keys (among other things) in an NSTextField
. See Apple's Technical Q&A QA1454, "How to make NSTextField accept tab, return and enter keys".
Seriously, though... just use NSTextView
. :)