Josh Kahane
Josh Kahane

Reputation: 17169

Check if View has been Removed or Not?

I have a UIView class which I am currently removing from my view by using from inside the class [self removeFromSuperview]. Hopefully that's the correct thing to do.

However, now from my view controller (of which I add this view to) I need to know when it has removed itself so that I can call a method when this happens.

Upvotes: 3

Views: 3037

Answers (6)

Diego Olmo Cejudo
Diego Olmo Cejudo

Reputation: 11

If you have removed the UIView

view.removeFromSuperview() 

you can check if it exists with the following code:

if !(view.superview != nil) {
   //no superview means not in the view hierarchy
}

Upvotes: 1

fatuous.logic
fatuous.logic

Reputation: 750

Not sure what sdk you are using - but I am using iOS 5 and I just use the following method in the superview:

-(void)willRemoveSubview:(UIView *)subview{
    if([subview isEqual:someView]){
      //do stuff
    }
    //you could do some stuff here too
}

Upvotes: 0

vikingosegundo
vikingosegundo

Reputation: 52237

The best choice would be to let the controller remove the view

[self.view removeFromSuperview];

and to know if the view was removed (or never added) you can ask

if(![self.view superview]) {
    //no superview means not in the view hierarchy
}

Upvotes: 0

Robotnik
Robotnik

Reputation: 3820

I'm assuming you are making the remove call after some sort of action, like a button press or something. if that is the case, set the buttons delegate to be the view controller, not the view class, and inside the action method in the view controller, call

[yourCustomView removeFromSuperview];

Upvotes: 0

Jim
Jim

Reputation: 73966

Generally speaking, the view shouldn't be doing things like removing itself. That's the job of the view controller.

If a UIView subclass can produce events that require the view hierarchy to be changed, I would define a delegate property for that view, and when an event occurs, call a method on that delegate. Then, when your view controller adds the view, it would set itself as the delegate and define the relevant method to handle the event.

Upvotes: 2

FeifanZ
FeifanZ

Reputation: 16316

You could have a delegate callback setting the controller as the view's delegate. When you're about to remove the view, make the delegate callback and implement the callback method in your controller.

The 'removeFromSuperview' has always seemed backwards to me… :(

Upvotes: 0

Related Questions