[英]removing view from superview crashing
I made a custom view that has a button inside it that would remove the view from its superview.我做了一个自定义视图,里面有一个按钮,可以从它的超级视图中删除视图。 The view is created from a view controller which is the superview.
该视图是从作为超级视图的视图控制器创建的。 I have setup the constraints for my view in my custom view class as it follows, but i suppose they are problematic.
我已经在我的自定义视图类中为我的视图设置了约束,如下所示,但我认为它们有问题。
// View Contstaints
translatesAutoresizingMaskIntoConstraints = false
leadingAnchor.constraint(equalTo: superview!.leadingAnchor, constant: 40).isActive = true
trailingAnchor.constraint(equalTo: superview!.trailingAnchor, constant: -40).isActive = true
heightAnchor.constraint(equalToConstant: 420).isActive = true
centerYAnchor.constraint(equalTo: superview!.centerYAnchor).isActive = true
backgroundColor = .white
layer.cornerRadius = 15
When i hit the button i get Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value from this particular constraint of the view当我按下按钮时,我得到 Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value from this specific constraint of the view
leadingAnchor.constraint(equalTo: superview!.leadingAnchor, constant: 40).isActive = true
How do i get around this?我如何解决这个问题? Thank you.
谢谢你。
Before you remove the view from its superview it might help to call NSLayoutConstraint.deactivate(yourView.constraints)
在从
NSLayoutConstraint.deactivate(yourView.constraints)
视图中删除视图之前,调用NSLayoutConstraint.deactivate(yourView.constraints)
可能会有所帮助
However it would be helpful to know where you are calling your constraint code inside the view's class.但是,了解在视图类中调用约束代码的位置会很有帮助。 In general it's best to set up your constraints in the viewController, and then remove the view when desired also from within the view controller, that might solve the problem.
一般来说,最好在 viewController 中设置约束,然后在需要时也从视图控制器中删除视图,这可能会解决问题。
I have found a way around it but not sure if it's efficient.我找到了解决方法,但不确定它是否有效。 what i did is override the removefromsuperview function and removed all the constraints and subviews there
我所做的是覆盖 removefromsuperview 函数并删除那里的所有约束和子视图
override func removeFromSuperview() {
for view in self.subviews{
view.removeFromSuperview()
}
NSLayoutConstraint.deactivate(self.constraints)
removeAllConstraintsFromView(view: self)
}
Though I am not sure if by doing so I'm deallocating my custom view from memory虽然我不确定这样做是否会从内存中释放我的自定义视图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.