Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a view be added to multiple other views safely, if so what does removeFromSuperView: do in that case?

Tags:

ios

I am wondering what happens if a single instance of a UIView object gets added as a subview of multiple other views simultaneously. If UIView:removeFromSubview: gets called then does it get removed from all superviews or just the currently displayed one?

For background:

I have a status-bar like view object that needs to be displayed within several different other views (each other view is managed by its own view controller).

[i.e. a) the user is in one view, b) something happens to make the status-bar-like view appear, c) the user switches to another view d)the status bar is still visible in the new view e) the status bar expires after a time and disappears from site. And so on]

Initially I implemented this by adding/removing it as required as a subview of the window, and this was managed by a singleton. However due to some complications with some animations I have instead added it as a subview of each of the main view's for each of the view controllers. Note that there are not multiple copies

When the view needs to be removed I am calling its removeFromSuperview:, and everything is all working perfectly.

However I am wondering what the situation is regarding the removal of the view, is it being fully removed or is there something else I need to do?

For example the view might get added to N view controller's views by calling addSubview as required (it will only get added to each view controller if that view controller actually launches) However when it is being removed I am only calling removeFromSuperview: for the view of currently loaded view controller, not all view controllers it might have been added to.

Next time I navigate to one of these other view controllers it displays fine without the view being there, even though I didn't explicitly call removeFromSuperView.

As I said everything is working as it is, however at the back of my mind I feel there might be something missing?

Hope this was understandable.

like image 960
Gruntcakes Avatar asked Aug 16 '12 18:08

Gruntcakes


1 Answers

You can only have it added to one view. Documentation is your friend!

  • (void)addSubview:(UIView *)view: Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
like image 160
ohr Avatar answered Nov 03 '22 00:11

ohr