12
votes

Hi everyone,

If I create NSTextField in my controller's view then all is fine - the field is editable. Unfortunately, I have to create NSTextField in new custom NSWindow. My code bellow produces a field which looks like without focus (text selection is gray) and is not editable (no cursor and no reaction to key strokes). I can change the text selection with mouse but that is all.

Do I have to enable the NSWindow to receive key strokes?

Appreciate your help, --Josef

      NSRect windowRect = [[self.window contentView] frame] ;
      NSWindow* uiWindow          = [[NSWindow alloc]  initWithContentRect:windowRect
                    styleMask:NSBorderlessWindowMask
                    backing:NSBackingStoreBuffered defer:YES];
      [uiWindow setBackgroundColor: [NSColor redColor/*clearColor*/]];
      [uiWindow setOpaque:NO];

      NSView* uiView = [[[NSView alloc] initWithFrame:NSMakeRect(0, 0, windowRect.size.width, windowRect.size.height)] autorelease];
      [uiView translateOriginToPoint:NSMakePoint(100, uiView.bounds.size.height/2)];
      uiView.wantsLayer = YES;

      [uiWindow setContentView:uiView];

      NSTextField *textField;
      textField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 800, 80)];
      [textField setFont:[NSFont fontWithName:@"Helvetica Bold" size:60]];
      [textField setStringValue:@"My Label"];
      [textField setBezeled:YES];
      [textField setDrawsBackground:YES];
      [textField setEditable:YES];
      [textField setSelectable:YES];
      [textField setEnabled:YES];

      [uiView addSubview:textField];


// THIS DOES NOT WORK
[self.window addChildWindow:uiWindow ordered:NSWindowAbove];

// THIS WORKS
//[_graphicView addSubview:uiView];
2
I just found that it is caused by window styleMask NSBorderlessWindowMask. If I use NSTitledWindowMask then it's fine. Is there a way to enable the keyboard for border-less window?PerfectGamesOnline.com

2 Answers

14
votes

You need to allow your custom window to become key window. By default, borderless windows cannot become key. In your NSWindow subclass, add the method canBecomeKeyWindow: :

- (BOOL)canBecomeKeyWindow
{
    return YES;
}



You can check if your borderless window is key window with this:

if([uiWindow isKeyWindow] == TRUE) {
    NSLog(@"isKeyWindow!");
}
else {
    NSLog(@"It's not KeyWindow!");
}



Furthermore, for a borderless window to accept key events, the class should implement acceptFirstResponder and return YES.

2
votes

If you can just change your styleMask:NSBorderlessWindowMask to style:NSTitledWindowMask, the above Code will work. However i have also tried adding editable TextFields to NSBorderlessWindow, but it didn't seem to work for me either.