我有同樣的問題,我解決了它在我的情況下,只需將alertController返回到單身人士,然後presentin在那裏。
在AlertView I類有一個簡單的警報,可以採取的標題和消息作爲輸入和顯示的只有一個OK按鈕以解除警報下面的代碼:
func alert(#alertTitle: String, alertMessage: String) -> UIAlertController {
var alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .Alert)
var okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(okButton)
return alertController
}
注意,在上述方法我不是將警報控制器呈現給視圖,而是將其返回給曾經調用該方法的人。
然後在我叫我做下面的代碼的方法的類:
**只是注意,如果我打電話報警的類是Objective-C的一個視圖控制器。我將在下面提供swift代碼以及**
// Creating an instance of the AlertView class and initializing it
AlertView *testAlert = [[AlertView alloc] init];
/* Creating a UIAlertController object and then calling the method I created in the AlertView class. This way the returned UIAlertController will be assigned to this UIAlertController
*/
UIAlertController *alertController = [testAlert alertWithAlertTitle:@"Genius!" alertMessage:@"Pure Genius"];
// Finally presenting the alert controller
[self presentViewController:alertController animated:true completion:nil];
注意:我發現您必須在ViewDidLoad之外執行此操作。它在ViewDidLoad中不起作用,並給出以下錯誤:
Attempt to present <UIAlertController: 0x1555118f0> on <ViewController: 0x155509790> whose view is not in the window hierarchy!
相反,您可以在viewDidAppear方法中執行此操作。
現在斯威夫特視圖控制器的版本:
// Created a function to show the alert
func showAlert() {
// Creating an instance of the AlertView class and initializing it
var testAlert : AlertView = AlertView()
/* Creating a UIAlertController object and then calling the method I created in the AlertView class. This way the returned UIAlertController will be assigned to this UIAlertController
*/
var alertController : UIAlertController = testAlert.alert(alertTitle: "Genius", alertMessage: "Pure Genius")
// Finally presenting the alert controller
self.presentViewController(alertController, animated: true, completion: nil)
}
,如果你想顯示在一個Singleton此警報的視圖控制器之外,那麼你可以檢索頂視圖控制器下面,然後提出警告還有一件事控制器到它:
目的 - C:
UIViewController *topViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
[topViewController presentViewController:alertController animated:true completion:nil];
夫特:
if let topViewController = UIApplication.sharedApplication().keyWindow?.rootViewController? {
topViewController.presentViewController(alertController, animated: true, completion: nil)
}
請添加一些(簡單)文字介紹您的答案,謝謝。 – 2015-09-13 15:51:56