2014-09-30 74 views
3

我想在應用程序進入後臺時單擊「取消」按鈕來關閉我的UIAlertController。以編程方式觸發UIAlertController的UIAlertAction

我已經設置了

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil]; 

然後後臺通知我appDidEnterBackground功能我:

- (void)appDidEnterBackground { 
    if (_alertController) { 
     UIAlertAction *cancelAction = [[_alertController actions] objectAtIndex:0]; 

     //HERE: is there a way to trigger the cancelAction?? 

     [_alertController dismissViewControllerAnimated:NO completion:nil]; 
    } 
} 

我正在掙扎是如何以編程方式觸發UIAlertAction。這可能嗎?

+0

我不認爲你可以編程式觸發你的'UIAlertAction'按。你可以嘗試複製代碼,或將其分支到全局聲明的方法中? – MCKapur 2014-09-30 12:15:07

+0

@MC卡普爾你的第二點有潛力。我已經爲UIAlertController(iOS7的/ UIAlertView)使用了一個單例,所以這些操作已經在全局範圍內定義了。我將如何在全球存儲塊,以便在應用程序進入後臺時調用它? – CharlesA 2014-09-30 12:56:42

+0

@MCKapur破解它 - 我添加了一個var到我的單例,保存完成塊操作。然後我在'appDidEnterBackground'中調用它。如果您發佈答案,我會接受。 – CharlesA 2014-09-30 13:10:56

回答

4

我回答了這個問題,使用了MCKapur的建議。

我已經有一個單身的UIAlertController。我所做的就是在我的單身定義一個變量來保存完成的動作:

@property (copy, nonatomic) void (^completion)(BOOL); 

後來,當我成立了UIAlertController表現出來,我也安裝完成代碼:

_completion = ^(BOOL cancelled) { 
    if (block) { 
     block (NO, nil); 
    } 
}; 

最後,我改變了appDidEnterBackground調用到:

- (void)appDidEnterBackground { 
    if (_alertController) { 
     if (_completion) { 
      _completion(NO); 
      _completion = nil; 
     } 
     [_alertController dismissViewControllerAnimated:NO completion:nil]; 
    } 
} 
相關問題