NSTextField在自定义NSWindow中无法编辑

Per*_*com 9 macos user-interface xcode cocoa objective-c

嗨,大家好,

如果我在控制器的视图中创建NSTextField,那么一切都很好 - 该字段是可编辑的.不幸的是,我必须在新的自定义NSWindow中创建NSTextField.我的代码产生一个看起来没有焦点的字段(文本选择是灰色的)并且不可编辑(没有光标,也没有对键击的反应).我可以用鼠标改变文本选择,但这就是全部.

我是否必须让NSWindow接收击键?

感谢你的帮助, - 约瑟夫

      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];
Run Code Online (Sandbox Code Playgroud)

Jus*_*Boo 11

您需要允许自定义窗口成为关键窗口.默认情况下,无边框窗口不能成为密钥.在您的NSWindow子类中,添加方法canBecomeKeyWindow::

- (BOOL)canBecomeKeyWindow
{
    return YES;
}
Run Code Online (Sandbox Code Playgroud)



你可以检查你的无边框窗口是否是关键窗口:

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



此外,对于接受键事件的无边界窗口,该类应该实现acceptFirstResponder并返回YES.