Search code examples
cocoasubclassnstextfieldfirst-responder

NSTextField subclass doesn't respect -acceptsFirstResponder?


I'm working with NSTextFields and enabling/disabling selection and editing, and I ran across some strange behavior in a sample app. I have a subclass of NSTextField called MyTextField; the only thing this subclass does is to deny first responder status whenever asked, as in:

@interface MyTextField : NSTextField
@end

@implementation MyTextField
- (BOOL)acceptsFirstResponder {
    return NO;
}
@end

However, when I place an instance of this text field in a .xib, then launch the app, I can still click into the text field and start editing it. Is the text field ignoring the return value of -acceptsFirstResponder?

I've tried a couple things to work around/diagnose this:

  • The text field's class is properly set to MyTextField instead of NSTextField in the .xib
  • If I place an NSLog statement before the return, it gets printed to console as expected
  • If I return NO for -becomeFirstResponder, it exhibits the same behavior: I can still edit the field
  • If I call [myTextField setSelectable:NO] in the view controller, it works as I expect: I'm no longer able to click into the field
    • However, if I return NO from -isSelectable and -isEditable (without calling -setSelectable: explicitly), I can still select text in (and edit) the field

What's going on here?


Solution

  • I'm not sure about this, but I think this has to do with the fact that the first responder is not actually the text field, but the field editor, which is a special (non-visible) text view object. Have a look at the "Working with the field editor" section of the "Text Editing Programming Guide" in the Apple docs to see an explanation.