如何删除特定的子视图?

时间:2012-05-03 16:18:33

标签: iphone objective-c subview

我已将subview(ViewController)添加到我的ViewController:

Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
[self.subView addSubview:location.view];

我怎样才能删除这个子视图?

我知道删除所有子视图是:

for (UIView *subview in [self.view subviews]) {

  [subview removeFromSuperview];

}

3 个答案:

答案 0 :(得分:50)

快速而肮脏:为视图添加标记,以便日后识别:

Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
UIView *viewToAdd = location.view;
viewToAdd.tag = 17; //you can use any number you like
[self.view addSubview:viewToAdd];

然后,删除:

UIView *viewToRemove = [self.view viewWithTag:17];
[viewToRemove removeFromSuperview];

更干净,更快速,更易于阅读和维护替代方案是创建一个变量或属性来访问视图:

在界面中:

@property (nonatomic, weak) UIView *locationView;

在实施中:

Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
UIView *viewToAdd = location.view;
self.locationView = viewToAdd;
[self.view addSubview:viewToAdd];

然后,删除:

[self.locationView removeFromSuperview];

那就是说,听取评论者关于玩其他ViewControllers视图的警告。如果你想这样做,请阅读 ViewController包含

答案 1 :(得分:7)

创建一个ivar,它可以为您提供对新viewController或仅视图的引用。我将在这里找到viewController

添加属性并合成它

// .h
@property (nonatomic, strong) Location *location;

// .m
@synthesize location = _location;

现在,当您创建位置时,设置ivar

Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
self.location = location;

[self.subView addSubview:location.view];

现在稍后将其删除

[self.location.view removeFromSuperview];

旁注

一般来说,将视图控制器的视图添加到另一个视图中这是一条痛苦的道路。有关这方面的一些解读,请参阅Abusing UIViewControllers

Location的命名可能不是很好,可能更适合称之为LocationViewController或类似内容。以这种方式进行一致的命名允许其他任何人(或将来你)能够轻松阅读并掌握这是一个viewController,而无需打开标题。

答案 2 :(得分:2)

您只需在视图中设置一个标识它的唯一标记即可。然后当你想要删除它。使用viewWithTag:(NSInteger)tag方法将其取回并仅删除此方法。

Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
location.tag = 8001; // 8001 is an exemple
[self.subView addSubview:location.view];

然后

UIView * v = [self.subView viewWithTag:8001];
if (nil != v) {
    [v removeFromSuperview];
}