简体   繁体   中英

Programmatically add a close button to nsview

I am trying to create Borderless window with windows style mask set to "NSBorderlessWindowMask". The window is subclassed and return "Yes" for canBecomeKeyWindow and canBecomeMainWindow. I have to get only minimize button in my view at top left corner. I am getting instance of minimise button object using "[NSWindow standardWindowButton:NSWindowMiniaturizeButton forStyleMask:NSBorderlessWindowMask]" and adding it as subview . The button is present in nsview. But is grayed out and is enabled and is not in Yellow also. Once I click it , it turns yellow. And on mouse hover "-" that appears in minimise button is not turning in. I tried [button setHighlighted:YES] which actually appears as clicked. I have added tracking area to get mouse hover.

_minButton = [NSWindow standardWindowButton:NSWindowMiniaturizeButton forStyleMask:NSBorderlessWindowMask];
[_minButton setFrameOrigin:NSMakePoint(_minButton.frame.origin.x + 7, _minButton.frame.origin.y)];
[_minButton setTarget:self.view.window];
[_minButton setAction:@selector(miniaturize:)];
[self.view addSubview:_minButton];
NSTrackingArea* trackingArea = [[NSTrackingArea alloc]
                                initWithRect:[_minButton bounds]
                                options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways
                                owner:self userInfo:nil];
[_minButton addTrackingArea:trackingArea];

- (void)mouseEntered:(NSEvent *)theEvent{
 [[_minButton cell]setHighlighted:YES];
}

- (void)mouseExited:(NSEvent *)theEvent{
[[_minButton cell]setHighlighted:NO];
}

try calling

[_minButton setNeedsDisplay:YES];

at the end of the method

This worked for me. It's a hack, but it worked.

- (void)windowDidBecomeKey:(NSNotification *)notification {

[_minButton highlight:YES];
[_minButton highlight:NO];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM