我想创建NSAlert(弹出窗口)show然后自动关闭。它同样点击按钮,它显示弹出扫描...,找到任何项目后,弹出扫描自动关闭。当弹出窗口显示时,用户无法单击我的应用程序上的任何按钮。我怎样才能做到这一点?非常感谢。
答案 0 :(得分:6)
以下代码可以帮助您
- (IBAction)showAlert:(id)sender {
//display the alert
self.myAlert = [NSAlert alertWithMessageText:@"Sample Test" defaultButton:@"OK" alternateButton:@"DO Nothing" otherButton:@"CANCEL" informativeTextWithFormat:@"TEST",nil];
[self.myAlert beginSheetModalForWindow:[self window]
modalDelegate:self
didEndSelector:@selector(errorAlertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
NSArray *buttonArray = [self.myAlert buttons];
NSLog(@"Button Arrays %@",buttonArray);
//Close by itself without a mouse click by the user
//Assuming the Default Button as the Second one "Do Nothing
NSButton *myBtn = [buttonArray objectAtIndex:2];
[myBtn performClick:self.myAlert];
}
答案 1 :(得分:0)
#import <Cocoa/Cocoa.h>
@interface NSAlert(AutoDismiss)
- (void) dismiss;
- (void) dismissAfter: (CGFloat) seconds completion: (void (^)(void)) completion;
@end
@implementation NSAlert(AutoDismiss)
- (void) dismiss {
NSButton* closeButton = self.buttons.lastObject;
if (closeButton) {
[closeButton performClick: self];
}
}
- (void) dismissAfter: (CGFloat) seconds completion: (void (^)(void)) completion {
__block NSAlert* weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[weakSelf dismiss];
if (completion) {
completion();
}
});
}
@end