2015-12-07 38 views
1

我在我的應用程序中有兩個視圖。主視圖(ViewController.swift)和側邊欄(SideBar.swift)。如果我點擊側邊欄中的按鈕,應該顯示一個UIAlertView(我在ViewController.swift中調用一個函數)。但該應用程序崩潰,因爲主視圖是零。你知道我該如何解決這個問題嗎?目前主視圖控制器中的警報視圖(從子類中調用)

我在功能(顯示警告)代碼:

let alertView = UIAlertController(title: "You need to log in first", message: "To access the special features of the app you need to log in first.", preferredStyle: .Alert) 
    alertView.addAction(UIAlertAction(title: "Login", style: .Default, handler: { (alertAction) -> Void in 
    })) 
    alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) 
    self.presentViewController(alertView, animated: true, completion: nil) 

崩潰日誌:

0x724160 <+60>: bl  0x75961c     ; function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded> of Swift.(_fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) ->()).(closure #2) 
-> 0x724164 <+64>: trap 
+0

你有沒有在側邊欄類參考ViewController.swift? – Robert

回答

2

有兩種解決方案,來我的心。

  1. 聲明一個協議並使用該委託將警報調用傳遞給MainView。

首先,在我們的SideBar.swift(讓我們稱之爲AlertDelegate)中定義一個協議。

protocol AlertDelegate { 

    func alertMain() 

} 

現在我們在SideBar.swift中創建一個委託變量。

var alertDelegate:AlertDelegate? 

然後我們使我們的MainView(ViewController.swift)堅持AlertDelegate協議。

class ViewController: UIViewController,foo,bar,AlertDelegate 

並添加AlertDelegate協議的功能。這裏是你將放置你的UIAlertController代碼的地方。

func alertMain(){ 

//Present UIAlertController 
} 

最後,我們必須着手的ViewController到委託alertDelegate

  • 存在,使用的AppDelegate KeyWindow您UIAlertController。我可能不會推薦這種方法,但這是你如何去做的。

    UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alert, animated: true, completion: nil) 
    
  • +0

    非常感謝您的回答!你能舉個例子說明我能做到嗎?我仍然在學Swift。 – 123

    +0

    有關詳細信息,請參閱我的編輯。 – Shane11

    相關問題