简体   繁体   中英

removeFromSuperview() suddenly no longer working

I have a UIView subclass loaded from a xib like so:

// The xib custom view
private var view: UIView!

override init(frame: CGRect) {
    super.init(frame: frame)
    xibSetup()
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    xibSetup()
}

/**
* Setting up the view
*/
private func xibSetup() {
    view = loadViewFromNib()

    // use bounds not frame or it'll be offset
    view.frame = bounds

    // Make the view stretch with containing view
    view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight

    // Adding custom subview on top of our view (over any custom drawing > see note below)
    addSubview(view)

}

/**
* Loading the custom view from a nib
*/
private func loadViewFromNib() -> UIView {
    // Load the nib
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "EditImageView", bundle: bundle)

    // Assumes UIView is top level and only object in PapControls.xib file
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
    return view
}

override func layoutSubviews() {
    super.layoutSubviews()
    blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
    blurView.frame = self.bounds
    blurView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tappedOnBlur:"))
}

Inside this view, I have a view called blurView that I'm adding behind a UITextView . It's added to the view like so:

self.view.insertSubview(blurView, belowSubview:textOverlay)

When I use the UITapGestureRecognizer on the blurView , the blurView should be removed using this code:

func tappedOnBlur(tapGesture: UITapGestureRecognizer?) {
    blurView.removeFromSuperview()
}

Originally, I was adding this subclass as a subview to a view and it worked perfectly. However, I am now using a UIViewController with its view set to the subclass so I can push it into view using a UINavigationController . Now that I've done this, if I try to call tappedOnBlur: , it doesn't remove it from the view. Strangely, if I use blurView.isDescendantOfView(self.view) it returns false (both before I try to remove it and after).

Does anyone know what's going on here? Thanks.

Just found out it's the way blurView is being loaded. I have moved the code in layoutSubviews() setting up blurView and it's working fine. I thought I could use layoutSubviews() like viewDidLoad() in a UIViewController but obviously not

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