I've added subview (ViewController) to my ViewController:
Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
[self.subView addSubview:location.view];
How can I latter remove this subview?
I know that for removing all subviews is:
for (UIView *subview in [self.view subviews]) {
[subview removeFromSuperview];
}
If the view's superview is not nil , the superview releases the view. Calling this method removes any constraints that refer to the view you are removing, or that refer to any view in the subtree of the view you are removing.
Adds a view to the end of the receiver's list of subviews.
Quick and dirty: Give your view a tag, so you can later identify it:
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];
Then, to remove:
UIView *viewToRemove = [self.view viewWithTag:17];
[viewToRemove removeFromSuperview];
A cleaner, faster, easier to read and to maintain alternative would be to create a variable or property to access the view:
In the interface:
@property (nonatomic, weak) UIView *locationView;
In the implementation:
Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
UIView *viewToAdd = location.view;
self.locationView = viewToAdd;
[self.view addSubview:viewToAdd];
Then, to remove:
[self.locationView removeFromSuperview];
That said, heed the warnings from commenters about playing with other ViewControllers' Views. Read up on ViewController containment if you want to do it.
Create an ivar that either gives you a reference to the new viewController or just the view. I'll go for the viewController here
Add a property and synthesize it
// .h
@property (nonatomic, strong) Location *location;
// .m
@synthesize location = _location;
Now when you create location set the ivar
Location *location = [[Location alloc] initWithNibName:@"Location" bundle:[NSBundle mainBundle]];
self.location = location;
[self.subView addSubview:location.view];
Now later to remove it
[self.location.view removeFromSuperview];
Generally it is a painful path to be adding a view controller's view to the view of another like this. For some light reading about this see Abusing UIViewControllers
Your naming of Location
is probably not excellent, it may be more appropriate to call it something like LocationViewController
or similar. Consistant naming in this way allows anyone else (or future you) to be able to easily read and grasp that this is a viewController without opening up the header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With