2013-02-21 87 views
1

我正在製作一個應用程序,該應用程序應該支持從iOS5開始的iOS版本。它使用UIAlertView,並且如果用戶按下主頁按鈕時可見,我希望在用戶返回到應用程序之前將其解除(即,當應用程序使用多任務重新打開時它消失了)。應用程序委託中的所有方法都將其顯示爲不可見(isVisible = NO),即使它在重新打開時仍然可見。有沒有辦法做到這一點?如何在主頁按鈕被按下時解除UIAlertView?

謝謝。

回答

7

或者你從UIAlertView中繼承的類,並添加NSNotification觀察員UIApplicationWillResignActiveNotification當通知時調用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或其他東西,只有一件事,你必須做它的ADAlertView(或任何其他類名稱)取代​​UIAlertView。 隨意使用此代碼示例(如果你不使用ARC,你應該[[NSNotificatioCenter defaultCenter] removeObserver:self]後添加到dealloc方法[super dealloc]

+0

這可能會起作用,但根據文檔*「UIAlertView類旨在按原樣使用,不支持子類」*。 – 2013-02-21 17:54:10

+0

無論如何,這是更好的,存儲一個鏈接到所有警報,你需要解僱,當應用程序進入後臺 – 2013-02-21 17:55:59

+1

@MartinR我相信他的類型的子類是「安全」。我認爲關於子類化的文檔中註釋的意圖是爲了修改用戶界面或者進行其他非安全漏洞的目的而使人們免於子類化。 – rmaddy 2013-02-21 18:03:23

4

在您的應用程序代理中保留對顯示的UIAlertView的引用。當您顯示警報時,請設置參考;當警報被解僱時,nil列出參考。

在您的應用程序代理的applicationWillResignActive:applicationDidEnterBackground:方法中,請在對警報視圖的引用上調用dismissWithClickedButtonIndex:animated:方法。按下「主頁」按鈕後,這會照顧到它。

請記住,applicationWillResignActive:將被稱爲諸如電話等事情,因此您需要決定是否在這種情況下解除警報,或者您應該通過電話保留它。

+3

I * *認爲是'applicationWillResignActive'也被稱爲臨時中斷,如來電或短信,所以'applicationDidEnterBackground'可能是更好的選擇。 – 2013-02-21 17:48:06

+0

@MartinR非常感謝您的評論!我編輯了答案來反映它。 – dasblinkenlight 2013-02-21 18:00:40

+0

這個,但絕對使用'applicationDidEnterBackground'! – Hyperbole 2013-02-21 18:00:49