简体   繁体   中英

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

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)

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.

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

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM