ios - 按下主页按钮时如何关闭 UIAlertView?

标签 ios objective-c xcode uialertview

我正在制作一个应该支持从 iOS5 开始的 iOS 版本的应用程序。它使用 UIAlertView,如果它在用户按下主页按钮时可见,我希望在用户返回应用程序之前将其关闭(即使用多任务重新打开应用程序时它消失了)。应用程序委托(delegate)中的所有方法都将其显示为不可见 (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,则应在 [super dealloc] 之后添加到 dealloc 方法 [[NSNotificatioCenter defaultCenter] removeObserver:self] )

关于ios - 按下主页按钮时如何关闭 UIAlertView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15008633/

相关文章:

ios - 在商业应用程序的 iOS 中使用 CorePlot 是否有任何限制?

objective-c - 当 NSTextField 的格式化程序更改格式时如何刷新?

cocoa - 添加预定义的框架,如(AddressBook.framework、CoreGraphics.framework)等。进入我的自定义框架(静态库)?

objective-c - 检索 Facebook 好友列表

c++ - Mac OSX - Yosemite 更新后每个 C++ 程序(甚至 Hello World)都出现段错误

ios - Xcode 8.2 无法设置权利成员资格

android - flex 移动项目中的多线程

ios - 你如何在 Swift 4 中创建文本字段填充?

ios - ReactiveCocoa : Chain a signal with a repeating signal

ios - 将 __block 参数传递给类方法(用于获取请求)