uiviewswiftsprite-kitskscene

removeFromSuperview doesn't work for UIView's added to SKScene


I am adding a UIView to the view of an SKScene. Later, when I wish to remove that UIView form its superview, using the standard method of uiview.removeFromSuperview does not seem to work. How should I be accomplishing this instead? Here is how I add the UIView:

func addContainerView() {

    let containerRect = CGRectMake(400, 24, 600, 720)
    smallerView = UIView(frame: containerRect)
    smallerView.backgroundColor = UIColor.redColor()
    self.view.addSubview(smallerView)
}

Here is how I am attempting to remove it:

func removeContainerView() {

    smallerView.removeFromSuperview()
}

This all takes place within the SKScene class, so here 'self' refers to that scene. Any thoughts?


Solution

  • First of all I wonder which version of swift your are using.

    self.view is optional in 1.2 hence your should type: self.view?.addSubview() if you are targeting swift 1.2

    I have tried in swift 1.2 to make a simple app

    class GameScene: SKScene {
    
      let subview = UIView()
    
      override func didMoveToView(view: SKView) {
    
        subview.frame = CGRectMake(0, 0, 100, 100)
        subview.backgroundColor = SKColor.orangeColor()
        self.view?.addSubview(subview)
      }
    
      override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        removeContainerView()
      }
    
      func removeContainerView() {
        subview.removeFromSuperview()
      }
    }
    

    The above code works very well. I can think of a couple of reasons your view doesn't get removed

    1. Are you sure that removeContainerView is actually called. Try to make a break point to see if it's called
    2. If you have set up your SKView in code something might have been setup wrong.
    3. Your subview is being deallocated or something

    To fully debug your problem we need to see some more code.

    What we need is:

    1. Declaration of your subview
    2. All functions that call removeContainerView()

    Even better would be to pastebin your SKScene class.