Ios 从其父视图控制器中删除子视图控制器时,应用程序崩溃
我正在尝试测试Ios 从其父视图控制器中删除子视图控制器时,应用程序崩溃,ios,swift3,uiviewcontroller,childviewcontroller,Ios,Swift3,Uiviewcontroller,Childviewcontroller,我正在尝试测试UIViewControllers之间的一些动画,在这个特殊的例子中,我有一个UIViewController,它添加了另一个UIVC作为它的子视图 一切正常,子视图被添加和显示,然后在子视图上我有一个UINavigationBar,它有一个取消按钮(dismise)作为其左栏按钮 当我单击该按钮时,我会启动一个函数,该函数试图从视图层次结构(从其父视图)中删除此显示的子视图 父视图中的代码: // ViewController -> Parent lazy var
UIViewControllers
之间的一些动画,在这个特殊的例子中,我有一个UIViewController
,它添加了另一个UIVC
作为它的子视图
一切正常,子视图被添加和显示,然后在子视图上我有一个UINavigationBar
,它有一个取消按钮(dismise)作为其左栏按钮
当我单击该按钮时,我会启动一个函数,该函数试图从视图层次结构(从其父视图)中删除此显示的子视图
父视图中的代码:
// ViewController -> Parent
lazy var presentButton: UIButton = {
let b = UIButton(type: .custom)
b.setTitle("Present", for: .normal)
b.setTitleColor(.black, for: .normal)
b.addTarget(self, action: #selector(didTapPresentButton), for: .touchUpInside)
return b
}()
lazy var childViewController: PresentedViewController = {
let viewController = PresentedViewController()
return viewController
}()
@objc func didTapPresentButton() {
addViewControllerAsChildViewController(childViewController: childViewController)
}
func addViewControllerAsChildViewController(childViewController: UIViewController) {
self.addChildViewController(childViewController)
childViewController.view.frame = CGRect.zero
self.view.addSubview(childViewController.view)
let newFrame = view.bounds
UIView.animate(withDuration: 2) {
childViewController.view.frame = newFrame
}
childViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
childViewController.didMove(toParentViewController: self)
}
正如您在上面看到的,当我单击“显示”按钮时,它将实例化子视图并在中设置动画,目前为止效果良好
子视图代码:
// ChildViewController -> Child (ofc)
@objc func didTapCancel() {
self.willMove(toParentViewController: nil)
self.view.removeFromSuperview()
self.removeFromParentViewController()
}
现在在子视图上,当我单击“取消”按钮时,我知道我必须调用removeFromParentViewController()
,才能将其正确删除,但如果我这样做并出现以下错误,应用程序将崩溃:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[dismissLayerTest.ChildViewController name]: unrecognized selector sent to instance 0x7fea2f60a920'
然后我尝试注释self.removeFromParentViewController()
行,这样做,应用程序不会崩溃,但在父视图控制器上,我可以通过打印self.childViewControllers.count
看到视图仍然连接到父视图,并显示1
你能看到问题出在哪里吗
谢谢我知道问题出在哪里了 在一些测试之后,我发现在使用
父子视图控制器时,不应该使用惰性
实例化
由于当我试图从parentViewController
中删除childViewController
时,我将childViewController
实例化为lazy
,错误表明无法识别发送到实例的选择器
,因此我发现属性指针选择器不知何故在parentViewController
上被解除分配,但没有我知道该解雇哪个孩子,因为它失去了参考资料
为了修复它,我删除了lazy
实例化,因此它始终保留在作用域中,现在我可以成功地将子项从其父作用域中删除
var childViewController: ChildViewController = {
let viewController = ChildViewController()
return viewController
}()
在代码中搜索“name”以查找错误所在。@YunCHEN没有任何与此相关的“name”属性或方法调用:/refere此链接可能有帮助:它没有帮助。此崩溃不会出现在您提到的链接上,示例中的视图层次结构也不相同谢谢!有趣的时刻!