为什么我以编程方式添加的 UIView 没有连接到我的 UIViewController?

Why is my UIView that I add programmatically not connected to my UIViewController?

我正在尝试在 Swift 中开发自定义警报视图控制器。我在故事板中为我的 AlertViewController 创建了一个 UIViewController。然后,当我需要显示它时,我执行以下操作:我将一个子视图添加到与原始视图一样大的原始视图并创建不透明背景。然后我向该视图添加第二个子视图以显示我的 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.cancelButtonreturnsnil

如果您知道我该如何解决这个问题,请告诉我,我们将不胜感激!提前致谢。

添加视图时,我还需要添加 viewController 本身,如下所示:

self.addChildViewController(vc)

然后,当我想删除它时,我将以下行添加到 "followingPressed" 方法中:

self.removeFromParentViewController()