删除基于标记的UIView子视图?

时间:2010-08-16 14:47:35

标签: iphone objective-c ipad

我正在创建一个这样的视图:

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];

这可能会在此视图控制器中多次发生,因此在创建这样的新视图之前,我想删除此标记可能存在的任何内容,我正在尝试这样做:

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

由于某种原因这不起作用,有人在这里看到我的问题吗?

我想我可以循环浏览所有视图并检查标签,但宁愿有更优雅和直接的解决方案。

1 个答案:

答案 0 :(得分:26)

问题是你可能只删除了几个视图吗?试试这个:

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

如果只有一个视图被创建/标记/删除,您还可以考虑添加一个属性来跟踪该视图,并写下:

[self.subView removeFromSuperview];
self.subView = qty;