我试图在Swift中开发自定义警报视图控制器。我在我的故事板中为我的AlertViewController创建了一个UIViewController
。然后,当我需要显示它时,我会执行以下操作:我在原始视图中添加一个subView,它与原始视图一样大,并创建不透明背景。然后我向该视图添加第二个子视图以显示我的AlertViewController.view
。以下是我用来显示AlertView的代码:
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
。
如果你有任何想法我怎么能解决这个问题,如果你能让我知道,那真的很感激!提前谢谢。
答案 0 :(得分:2)
当我添加视图时,我还需要添加viewController本身,具有以下内容:
self.addChildViewController(vc)
然后,当我想删除它时,我将以下行添加到“followingPressed”方法:
self.removeFromParentViewController()