iOS4.0以后UIAlertView自动关闭
工程中有很多的UIAlertView弹出,但有时候弹出状态进入后台,希望它能自动关闭掉,这个文章就是说这个自动关闭的问题。
通过创建UIAlertView的子类,每次创建一个UIAlertView实例的时候就往通知中心存入一条通知,等程序进入到后台时,发一条消息给UIAlertView,让它dismiss,思路就是这么个思路,当然也可以创建UIAlertView的category,思路是一样的,就是category就覆盖掉UIAlertView本身的创建方法,由于这次遇到的是中途有这个需求,采用后者影响就大,所以还是采用子类来实现
直接上代码:
UIAlertViewAutoDismiss.h
#import <uikit uikit.h="">
@interface UIAlertViewAutoDismiss : UIAlertView
@end
</uikit>
UIAlertViewAutoDismiss.m
#import "UIAlertViewAutoDismiss.h"
@implementation UIAlertViewAutoDismiss
- (id)initWithTitle:(NSString *)title
message:(NSString *)message
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ... {
if ((self = [super initWithTitle:title
message:message
delegate:delegate
cancelButtonTitle:cancelButtonTitle
otherButtonTitles:nil, nil])) {
va_list args;
va_start(args, otherButtonTitles);
for (NSString *anOtherButtonTitle = otherButtonTitles;
anOtherButtonTitle != nil;
anOtherButtonTitle = va_arg(args, NSString*)) {
[self addButtonWithTitle:anOtherButtonTitle];
}
va_end(args);
if ([[UIDevice currentDevice].systemVersion intValue] >= 4) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
}
}
return self;
}
- (void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void) applicationDidEnterBackground:(id) sender {
[self dismissWithClickedButtonIndex:[self cancelButtonIndex] animated:NO];
}
@end