[英]How to dismiss UIAlertView when home button is pressed?
我正在制作一个应支持iOS5以后的iOS版本的应用。 它使用UIAlertView,如果用户按下主屏幕按钮时可见,则希望在用户返回应用程序之前将其关闭(即,当使用多任务处理重新打开应用程序时它消失了)。 应用程序委托中的所有方法都将其显示为不可见(isVisible = NO),即使重新打开后仍可见。 有没有办法做到这一点?
谢谢。
或者,您从UIAlertView继承您的类,并为UIApplicationWillResignActiveNotification添加NSNotification观察器,并在发生通知时调用alertview方法dismissWithClickedButtonIndex:
示例:.h文件
#import <UIKit/UIKit.h>
@interface ADAlertView : UIAlertView
@end
.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
使用从UIAlertView继承的您自己的类,您无需存储指向alertview或其他内容的链接,只需执行一件事即可将其替换为UIAlertView到ADAlertView(或任何其他类名)。 随意使用此代码示例(如果您未使用ARC,则应在[[NSNotificatioCenter defaultCenter] removeObserver:self]
之后添加到dealloc方法[super dealloc]
[[NSNotificatioCenter defaultCenter] removeObserver:self]
)
在您的应用程序委托中保留对显示的UIAlertView
的引用。 显示警报时,请设置参考。 当被驳回了警报, nil
出参考。
在您的应用程序委托的applicationWillResignActive:
或applicationDidEnterBackground:
方法中,在对警报视图的引用上调用dismissWithClickedButtonIndex:animated:
方法。 这将在按“主页”按钮时将其关闭。
请记住,将针对诸如电话之类的事件调用applicationWillResignActive:
:,因此您需要确定是否要在这种情况下关闭警报,或者是否应该通过电话保持警报状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.