In any case, so that (wrapping) the NSTextField records the carriage return when the return key is pressed?

I want to use a text box for wrapping, which could potentially contain a carriage return in my application. Is there a way to get an NSTextField object to write a carriage return to the text area instead of sending its action to its target when the return key is pressed?

+3
source share
4 answers

This is described in Technical Q & A QA1454 , which also lists the reasons why instead NSTextViewshould be used NSTextFieldin this case.

In the delimiter of the text field, you can implement the following method:

- (BOOL)control:(NSControl*)control
    textView:(NSTextView*)textView
    doCommandBySelector:(SEL)commandSelector
{
    BOOL result = NO;

    if (commandSelector == @selector(insertNewline:))
    {
        // new line action:
        // always insert a line-break character and don’t cause the receiver
        // to end editing
        [textView insertNewlineIgnoringFieldEditor:self]; 
        result = YES;
    }

    return result;
}
+10
source

, , ( ) . NSTextField -textShouldEndEditing: :

-(BOOL)textShouldEndEditing:(NSText *)textObject {
    NSEvent * event = [[NSApplication sharedApplication] currentEvent];
    if ([event type] == NSKeyDown && [event keyCode] == 36) {
        [self setStringValue:[[self stringValue] stringByAppendingString:@"\n"]];
        return NO;
    }
    else {
        return [super textShouldEndEditing:textObject];
    }
}
+2

I found that a combination of Sean and Bevirius works best for me. Sean's answer suggests that a new line should always be added to the end (instead of, for example, where the user cursor is located).

-(BOOL)textShouldEndEditing:(NSText *)textObject 
{
    NSEvent * event = [[NSApplication sharedApplication] currentEvent];
    if ([event type] == NSKeyDown && [event keyCode] == 36) 
    {
        [textObject insertNewlineIgnoringFieldEditor:nil];
        return NO;
    }
    else 
    {
        return [super textShouldEndEditing:textObject];
    }
}
+1
source

Quick version:

override func textShouldEndEditing(textObject: NSText) -> Bool {
    let event = NSApplication.sharedApplication().currentEvent
    if event?.type == NSEventType.KeyDown && event?.keyCode == 36 {
        self.stringValue = self.stringValue.stringByAppendingString("\n")
        return false
    } else {
        return super.textShouldEndEditing(textObject)
    }
}
0
source

All Articles