9

I created a button, and a have a little problem: When the my app launches, the button is selected. How do I disable this selection?

Example:

A window with two buttons. The first (left) has a blue glow around it, and the second (right) does not.

Ky -
  • 30,724
  • 51
  • 192
  • 308
Alexander
  • 93
  • 4
  • Note that by doing this you’re removing visual feedback for the user. Given two buttons without focus rings, the user won’t know which one will be clicked in case the Space key is pressed. Pressing Tab will alternate between the buttons but, again, the user won’t have visual feedback of that. –  Apr 26 '11 at 08:28

3 Answers3

5

First, you should know that, by default, buttons can't get focus. A user would have to have selected System Preferences > Keyboard > Shortcuts > Full Keyboard Access: All Controls. If they've done that, they may want a button to initially have focus.

Anyway, the proper way to do this is to call [theWindow makeFirstResponder:nil] sometime after showing it the first time. When to do this depends on exactly how the window gets shown. If you show it explicitly in code, then you can make the call just after that. If it's shown because its Visible at Launch flag is set in its NIB, then you'd do it after the NIB is loaded. Etc.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
5

Caveat: This answer is incomplete: It just hides the focus ring (without preventing the selection). There's little benefit in this solution.

Set your button's focus ring type to none:

[myButton setFocusRingType:NSFocusRingTypeNone];

You can also set this option in the XIB.

Community
  • 1
  • 1
Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • 5
    This seems like a poor solution. Now, the user can navigate using Tab, but only the second button will highlight when it's focused, yet the first will focus without being highlighted. – Ky - Aug 22 '16 at 20:23
  • 4
    This should _not_ be acceptable. This just makes it so the user can't tell the button is selected. This does not stop the button from being selected at all. – Ky - Aug 09 '18 at 20:03
3

Something should always be first responder in a window, if anything can be. Normally, only a few controls like text fields can become first responder, but when a user has Full Keyboard Access enabled, it's normal for a button to be selected by default.

If you don't want this particular button to start selected, set the window's initialFirstResponder to another control.

I'd advise against using -[NSWindow makeFirstResponder:nil]. The window will start with nothing selected, but the button will become selected as soon as the user hits tab. This is unusual for Mac apps because there's no way to get the window back into the "nothing selected" state as a user.

s4y
  • 50,525
  • 12
  • 70
  • 98