2016-04-29 101 views
0

我想在Swift中開發一個自定義警報視圖控制器。我在我的AlertViewController的故事板中製作了一個UIViewController。然後,當我需要顯示它時,我執行以下操作:向原始視圖添加一個子視圖,該視圖與原始視圖一樣大,並創建不透明背景。然後我添加第二個子視圖到該視圖來顯示我的AlertViewController.view。以下是我用來顯示我的AlertView的代碼:爲什麼我的UIView以編程方式添加未連接到我的UIViewController?

let vc = self.storyboard!.instantiateViewControllerWithIdentifier("topicAlertView") as! EditTopicAlertViewController 
let alertView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)) 

alertView.backgroundColor = UIColor(colorLiteralRed: 23/255.0, green: 62/255.0, blue: 67/255.0, alpha: 0.75) 

let alertBox = UIView(frame: CGRect(x: alertView.bounds.size.width/2.0 - 150.0, y: alertView.bounds.size.height/2.0 - 100.0, width: 300, height: 200)) 


alertBox.addSubview(vc.view) 
alertView.addSubview(alertBox) 

這可以正常顯示我的警報視圖。但是,它好像完全沒有連接到它的UIViewController:「EditTopicAlertViewController」。比如我有一個連接到它的一個動作一個取消按鈕,它不是在所有叫,我也可以添加

vc.cancelButton.addTarget(self, action: #selector(EditTopicAlertViewController.cancelPressed(_:)), forControlEvents: .TouchUpInside) 

因爲vc.cancelButton返回nil

如果您有任何想法,我該如何解決這個問題,如果您能讓我知道,我會非常感激!提前致謝。

+1

請在「UIViewController」的文檔中閱讀「實現容器視圖控制器」。 – rmaddy

回答

2

當我添加的看法我還需要添加的viewController本身,有以下:

self.addChildViewController(vc) 

然後,當我想刪除它,我下面的行添加到「followingPressed」的方法:

self.removeFromParentViewController() 
+2

幹得好。你自己找到了答案。 (投了票。)rmaddy的評論有幫助嗎? –

相關問題