Problems setting FirstResponder in Cocoa Mac OSX

纵然是瞬间 提交于 2019-12-03 16:27:06

You are making this much harder than it needs to be.

In Interface Builder, set the initialFirstResponder outlet of your window to point to your text field.

That's it.

If you absolutely must do it programmatically, use:

[window setInitialFirstResponder:yourTextField];

Remember, if you're fighting with Cocoa to do something that seems like it should be simple, then you're probably doing it wrong.

Override viewDidAppear, and within said method, call the NSTextField's becomeFirstResponder method.

Note that in my own work, viewWillAppear has proven to be too early for said call, whether using the NSTextField's becomeFirstResponder method or the NSWindow's makeFirstResponder method.

The trouble is that self.view.window is null in the first view controller's viewDidLoad method until after applicationDidFinishLaunching exits. So, becomeFirstResponder doesn't work in viewDidLoad. Try delaying the setting of the first responder, like so:

[_yourTextField performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.1];

You should never try to set first responder in viewDidLoad method because window is still nil at that point. Use viewWillAppear instead:

- (void)viewWillAppear
{
    [super viewWillAppear];
    if (!_started) {
        _started = YES;
        [self.view.window makeFirstResponder:_yourView];
    }
}

Apple also once said that you should never call becomeFirstResponder directly. Use [yourWindow makeFirstResponder:yourView]; instead.

Just read the documentation:

becomeFirstResponder

Notifies the receiver that it’s about to become first responder in its NSWindow.

[...]

Use the NSWindow makeFirstResponder: method, not this method, to make an object the first responder. Never invoke this method directly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!