Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove UIView subview based on tag?

I am creating a view like this:

UILabel *qty = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
qty.backgroundColor = [UIColor whiteColor];
qty.text =[NSString stringWithFormat:@" Qty: %@", currentQty];
qty.alpha = 0.5;
[qty setTag:999];
[self.view addSubview:qty];
[qty release];

This can happen multiple times in this view controller so before I create a new view like this I want to remove any that might exist with this tag, I am trying this:

UIView *removeView  = [self.view viewWithTag:999];
[removeView removeFromSuperview];

This is not working for some reason, anyone see my problem here?

I guess i could loop through all the views and check the tag but would rather have a more elegant and direct solution.

like image 731
Slee Avatar asked Aug 16 '10 14:08

Slee


1 Answers

Is the issue that you're possibly only removing one view of several? Try this:

UIView *removeView;
while((removeView = [self.view viewWithTag:999]) != nil) {
    [removeView removeFromSuperview];
}

If there's only one view that's getting created/tagged/removed, you also might consider just adding a property to track that view, and writing:

[self.subView removeFromSuperview];
self.subView = qty;
like image 66
Seamus Campbell Avatar answered Oct 20 '22 13:10

Seamus Campbell