快速而肮脏:给您的视图一个标签,以便您以后识别它:
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];
也就是说,请注意评论者关于使用其他 ViewController 的 View 的警告。如果您想这样做,请阅读ViewController 包含。