开发者

How we use Shift+Enter for line break in NSTextField- Cocoa

I want to line bre开发者_运维问答ak using shift+enter in TextField(Control+Enter is working) I don't want to use TextView because using this Enter Key Action is not performing..


The standard way to do this is option-return, and it works for free.


With this code when user presses Enter key you can sent an comment for example and when user presses Shift+Enter key the default behaviour of NSTextView is executed which it is to insert an line break. In my opinion this is a better solution than to use an NSTextField in this case.

- (BOOL)textView:(NSTextView *)aTextView doCommandBySelector:(SEL)aSelector {
    if (aSelector == @selector(insertNewline:)) {
        NSEvent * event = NSApp.currentEvent;
        if ((event.modifierFlags & NSShiftKeyMask) != NSShiftKeyMask) {
            //Do some when only the enter key is pressed
            return YES;
        }
    }
   return NO;
}


Here's how I did it: Within control:textView:doCommandBySelector: of NSTextFieldDelegate, capture the insertNewline: command and check if the current event has the shift modifier flag.

- (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor doCommandBySelector:(SEL)commandSelector {
    if (commandSelector == @selector(insertNewline:) &&
        [[[NSApplication sharedApplication] currentEvent] modifierFlags]
        & NSShiftKeyMask) {

        [fieldEditor insertNewlineIgnoringFieldEditor:self];
        return YES;
    }

    return NO;
}


Alternatively, if a text view would be more appropriate for your app than a text field, then that's what you should use.

I wrote one that can send action messages. Here's the header and the implementation. It's under a BSD license.


Thanks Peter it works I add following in code int flags = [event modifierFlags]; BOOL shift = ( flags & NSShiftKeyMask ) ? YES : NO;

if (([event keyCode] == enterKey1 || [event keyCode] == enterKey2) && !shift) {
    window = [self window];
    [window makeFirstResponder:[window contentView]];

    [NSApp sendAction:action to:target from:self];
}

but now able to set focus on texView after action on textField I was using [textField selecttext];

for TextView I tried [theTextView setSelectedRange: NSMakeRange(0,0)]; but not works

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜