remove UIView subview based on tag?

2020-06-17 05:45发布

问题:

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.

回答1:

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;