按下主页按钮时如何解除UIAlertView?

Mac*_*206 1 xcode objective-c uialertview ios

我正在制作一款应该支持iOS5以上iOS版本的应用.它使用UIAlertView,如果在用户按下主页按钮时可见,我希望在用户返回应用程序之前将其解除(即当使用多任务重新打开应用程序时它已消失).app delegate中的所有方法都将其显示为不可见(isVisible = NO),即使它在重新打开时仍然可见.有没有办法做到这一点?

谢谢.

Iva*_*vyi 7

或者您从UIAlertView继承您的类并为UIApplicationWillResignActiveNotification添加NSNotification观察者,并在发生通知时调用alertview方法 dismissWithClickedButtonIndex:

示例:.h文件

#import <UIKit/UIKit.h>

@interface ADAlertView : UIAlertView

@end
Run Code Online (Sandbox Code Playgroud)

.m文件

#import "ADAlertView.h"

@implementation ADAlertView

- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id) initWithTitle:(NSString *)title
             message:(NSString *)message
            delegate:(id)delegate
   cancelButtonTitle:(NSString *)cancelButtonTitle
   otherButtonTitles:(NSString *)otherButtonTitles, ... {
    self = [super initWithTitle:title
                        message:message
                       delegate:delegate
              cancelButtonTitle:cancelButtonTitle
              otherButtonTitles:otherButtonTitles, nil];

    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
             selector:@selector(dismiss:)
                 name:UIApplicationDidEnterBackgroundNotification
               object:nil];
    }

    return self;
}

- (void) dismiss:(NSNotification *)notication {
    [self dismissWithClickedButtonIndex:[self cancelButtonIndex] animated:YES];
}

@end
Run Code Online (Sandbox Code Playgroud)

使用从UIAlertView继承的自己的类,您不需要存储指向alertview或其他内容的链接,只需要将UIAlertView替换为ADAlertView(或任何其他类名).随意使用此代码示例(如果您不使用ARC,则应[super dealloc]在之后添加到dealloc方法[[NSNotificatioCenter defaultCenter] removeObserver:self])