Reputation: 3
While adding blur effect to subview giving error:
unexpectedly found nil while unwrapping an Optional value
For first time it working fine, if i try second time its giving above error.
outlets:
@IBOutlet var mesgText_view: UIView!
var blurEffectView: UIVisualEffectView!
CODE:
func OpenSubMesgView(_ sender : UIButton) {
print(sender.tag)
print("ARRAY VALUES FROM CELL",totlObservationArray.object(at: sender.tag))
mesgText_view.alpha = 1
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)
blurEffectView.addSubview(mesgText_view)
}
@IBAction func closeMesgview(_ sender:UIButton) {
mesgText_view.alpha = 0;
self.blurEffectView.removeFromSuperview()
}
Upvotes: 0
Views: 732
Reputation: 119272
self.blurEffectView.removeFromSuperview()
I'm going to guess that this and / or mesgText_view
refers to an outlet, declared as weak like this:
@IBOutlet weak var blurEffectView: UIVisualEffectView!
Weak variables are set to nil if nothing holds a strong reference to them. If you remove a weakly held view from its superview, it will be set to nil and the next time you try to reference it, your app will crash.
The first time your code runs it will be removing some weak outlet from its superview. Since it's a weak property, nothing else has a reference to it and it is made nil. The second time your code runs, it accesses the outlet which is now a nil implicitly unwrapped optional, causing your crash.
You could also make the outlet a strong reference by removing the weak
keyword from the declaration. This would allow you to remove it from its superview without it being nilled out.
Upvotes: 1