【问题标题】:How to auto dismiss NSAlert on OSX?如何在 OSX 上自动关闭 NSAlert?
【发布时间】:2013-08-27 07:59:51
【问题描述】:

我想创建 NSAlert(弹出)节目然后自动关闭。同样点击按钮,它显示弹出扫描...,找到任何项目后,弹出扫描自动关闭。当弹出显示时,用户无法单击我的应用程序上的任何按钮。我怎样才能做到这一点?非常感谢。

【问题讨论】:

    标签: objective-c macos cocoa


    【解决方案1】:

    下面的代码会帮助你

    - (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];
    

    }

    【讨论】:

    • 谢谢,但我不想添加任何警报按钮。你能告诉我在调用另一个函数时如何关闭 nsalert 吗?
    • 这对我有用:[self.myAlert.window orderOut:self]; [self.myAlert.window 关闭];
    【解决方案2】:
    #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
    

    【讨论】:

      猜你喜欢
      • 2013-01-01
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      相关资源
      最近更新 更多