Set Keyboard Focus to NSView?

Discussion in 'Mac Programming' started by Gandolfmatt, Mar 5, 2010.

  1. Gandolfmatt macrumors member

    Joined:
    Jul 18, 2008
    #1
    Hey, what's the code to set keyboard focus to an NSView?
    I have a textField which deselects when the Enter key is hit, and I need a way for it to select the NSView to respond to key presses.
    Any ideas?


    Thanks,
    -Gan
     
  2. Sydde macrumors 68020

    Sydde

    Joined:
    Aug 17, 2009
    #2
    Examine the documentation for NSWindow.
     
  3. Gandolfmatt thread starter macrumors member

    Joined:
    Jul 18, 2008
    #3
    I've searched without success.
    Most of my code is within the NSView, even my textField code is. Now when you click enter on the textField it runs this:
    Code:
    [self sendMessage:[textField stringValue]];
    [textField setStringValue:@""];
    [textField setSelected:FALSE];
    That deselects the textField but there's no setSelect command for an NSView. I've noticed that you need to click the NSView to select it, is there a way you could do that programmatically instead of having to click the NSView for it to accept key response?


    -Gan
     
  4. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #4
    Try something like this
    Code:
    [[myView window] makeFirstResponder:myView];
     
  5. Gandolfmatt thread starter macrumors member

    Joined:
    Jul 18, 2008
    #5
    I'm sure that'd work though this code throws an exception:
    Code:
    [textField setSelected:FALSE];
    Which does deselect the textField but also ignores all code after. Any safe way to deselect a textField?


    Thanks,
    -Gan
     
  6. Gandolfmatt thread starter macrumors member

    Joined:
    Jul 18, 2008
    #6
    Got it:
    Code:
    [[[[NSApplication sharedApplication] delegate] window] selectNextKeyView: [[[NSApplication sharedApplication] delegate] window]];
    This causes it to switch to the next view. If there's more than one view it could get messy.


    -Gan
     
  7. Sydde macrumors 68020

    Sydde

    Joined:
    Aug 17, 2009
    #7
    I believe you can abbreviate [NSApplication sharedApplication] to NSApp (it looks a tiny bit cleaner, to me anyway).
     

Share This Page