How can I make my NSTextField NOT highlight its text when the application starts?

前端 未结 3 1580
無奈伤痛
無奈伤痛 2021-02-07 16:10

When my application launches, the first NSTextField is being selected like this:

I can edit the NSTextField fine, but when I press enter to end the editing, th

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-07 16:49

    Your text field is selecting the text, due to the default implementation of becomeFirstResponder in NSTextField.

    To prevent selection, subclass NSTextField, and override becomeFirstResponder to deselect any text:

    - (BOOL) becomeFirstResponder
    {
        BOOL responderStatus = [super becomeFirstResponder];
    
        NSRange selectionRange = [[self  currentEditor] selectedRange];
        [[self currentEditor] setSelectedRange:NSMakeRange(selectionRange.length,0)];
    
        return responderStatus;
    }
    

    The resulting behavior is that the field does not select the text when it gets the focus.

    To make nothing the first responder, call makeFirstResponder:nil after your application finishes launching. I like to subclass NSObject to define doInitWithContentView:(NSView *)contentView, and call it from my NSApplicationDelegate. In the code below, _window is an IBOutlet:

    - (void) applicationDidFinishLaunching:(NSNotification *)aNotification {
        // Insert code here to initialize your application
    
        [_menuController doInitWithContentView:_window.contentView];
    }
    

    The reason your field is getting focus when the application starts is because the window automatically gives focus to the first control. It determines what is considered first, by scanning left to right, top down (it scans left to right first, since a text field placed at the top right will still get focused). One caveat is that if the window is restorable, and you terminate the application from within Xcode, then whatever field was last focused will retain the focus state from the last execution.

提交回复
热议问题