views:

105

answers:

2

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.

A: 

It looks like you are just creating a reference to the view you want to remove and removing that. try using [[self.view viewWithTag:999] removeFromSuperview];

Jesse Naugher
Eh? How is that different from the OP's code, other than being in one line?
walkytalky
+2  A: 

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;
Seamus Campbell
nice, works like a champ - thank you!
Slee