Search code examples
objective-ccocoanswindownstextfield

NSTextfield not accepting keyevents on NSWindow which has NSTitledWindowMask


I have started coding cocoa app. I have created a NSwindow with initWithContentRect. I have created a NSTextField. I can not get any of the keyboard events. It is selectable. I also explicitly set editable to true. I have realized there are similar questions but they are mostly about the responder, key window and Borderlesswindow style.

I have a NSWindows which has a titled window mask , is the key window and it is selected when I set it to be the first responder.

But why cant I type anything into the box.

int style = NSClosableWindowMask  |NSTexturedBackgroundWindowMask | NSTitledWindowMask | NSMiniaturizableWindowMask;

window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 130, 150)
styleMask:style backing:NSBackingStoreBuffered defer:NO];

CGFloat height=20;
NSTextField  * username=[[NSTextField alloc] initWithFrame:NSMakeRect(10, NSHeight(window.frame)-80, 100, height)];
[username setEditable:true];
[window.contentView addSubview:username ];

Is it because I need to create a subclass of NSwindow. I see this is suggested when the style is NSBorderlessWindowMask and by overriding

canBecomeKeyWindow it is suggested to solve the issue.

But I am not using NSBorderlessWindowMask.

What am I missing? Any help is appreciated.


Solution

  • From your comment, you say you don't have a Info.plist file. I'm guessing your app isn't even bundled. This is a crucial fact that you left out of your question, which only makes it hard for people to help you.

    First, you should create apps the normal way. Make a bundled app with a main NIB. Follow the standard template, except delete the window from the main NIB and use separate window NIBs.

    If you aren't equipped to understand what's going wrong with a "manually" constructed app and fix it, then you really shouldn't be going that route.

    That said, an unbundled app will start life as a background-only process. What little interactivity you're seeing is, more or less, a bug. You can transform your app into a foreground app by setting the activationPolicy of the application object (instance of NSApplication or a subclass) to NSApplicationActivationPolicyRegular. Then, make it the active app by calling [NSApp activateWithOptions:NSApplicationActivateIgnoringOtherApps].