Cách tiếp cận Tôi sử dụng là tương tự như câu trả lời ở trên, ngoại trừ tôi có tất cả mọi thứ kết hợp thành một phương pháp thay vì sử dụng hai IBActions riêng biệt.
Trước tiên, tôi tuyên bố các thuộc tính sau
@property (strong, nonatomic) NSStatusItem *statusItem;
@property (strong, nonatomic) NSEvent *popoverTransiencyMonitor;
@property (weak, nonatomic) IBOutlet NSPopover *popover;
@property (weak, nonatomic) IBOutlet NSView *popoverView;
sau đó trong awakeFromNib tôi thiết lập các mục trên thanh trạng thái
- (void)awakeFromNib {
self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
self.statusItem.title = @"Title";
self.statusItem.highlightMode = YES;
self.statusItem.action = @selector(itemClicked:);
}
tiếp theo là phương pháp đó được gọi là khi mục thanh trạng thái được nhấp
- (void)itemClicked:(id)sender {
[[self popover] showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMinYEdge];
if (self.popoverTransiencyMonitor == nil) {
self.popoverTransiencyMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDownMask | NSRightMouseDownMask | NSKeyUpMask) handler:^(NSEvent* event) {
[NSEvent removeMonitor:self.popoverTransiencyMonitor];
self.popoverTransiencyMonitor = nil;
[self.popover close];
}];
}
}
làm cho cửa sổ bật lên xuất hiện và cũng đóng khi người dùng nhấp ngoài tầm nhìn.
Lưu ý rằng trong Trình tạo giao diện, bạn phải đặt hành vi của cửa sổ bật lên thành Tạm thời để cửa sổ bật lên sẽ đóng khi người dùng nhấp vào mục trạng thái.
Đối với hành vi nhất quán với hành vi của các mục trạng thái hệ thống: 'addGlobalMonitorForEventsMatchingMask: NSLeftMouseDownMask | NSRightMouseDownMask' - để các nhấp chuột phải cũng đóng cửa sổ bật lên. – inket