简体   繁体   中英

Disable Option-Enter line breaks in NSTextField?

I want to disallow entering a new-line character in my NSTextField, which by default is possible by typing Option-Enter (or Option-Return).

While I found some pages explaining how to allow line breaks without having to use the Option modifier, I couldn't find anything for disabling line breaks altogether.

How can this be done?

You could create a subclass of NSFormatter and implement the isPartialStringValid:... method to block the newline.

- (BOOL)isPartialStringValid:(NSString **)partialStringPtr 
       proposedSelectedRange:(NSRangePointer)proposedSelRangePtr 
              originalString:(NSString *)origString 
       originalSelectedRange:(NSRange)origSelRange 
            errorDescription:(NSString **)error
{
    // the user may have:
    // -- deleted the left most character
    // -- deleted the last character and we have an empty string
    // both cases are valid
    if (proposedSelRangePtr->location == 0)
        return YES;

    unichar theChar = [*partialStringPtr characterAtIndex:proposedSelRangePtr->location - 1];

    if ([[NSCharacterSet newlineCharacterSet] characterIsMember:theChar]) {
        *error = nil;
        NSBeep();
        return NO;
    }

    return YES;
}

May I ask why you wish to disable this feature? It's a pretty standard part of the OS. Bear in mind that the user might well paste in some string from elsewhere that contains a line break and they'll then edit to their needs. Would it perhaps be better to leave this feature intact, but use an NSFormatter to strip out everything after the line break when it is time to copy the value out of the view to the model?

I do the following code for preventing from line-break issue in case of using Control, Option + Enter (Return).

- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
{
    if ((commandSelector == @selector(insertNewlineIgnoringFieldEditor:)) || (commandSelector == @selector(insertLineBreak:)))
    {
        return YES;
    }

    return NO;
}

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