Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a view from one view and add it to another

I am trying to find all my views that are in the nib and add them to my content view.

This is what I have, It successfully removes the view from self.view but it does not add it to self.contentView

for (UIView *view in self.view.subviews) {
    if (view.tag != 666) {
        [view removeFromSuperview];
        [self.contentView addSubview:view];
    }
}

Any help would be appreciated.

like image 226
Gary Kagan Avatar asked Jun 15 '12 03:06

Gary Kagan


2 Answers

The issue in your code is, when you call removeFromSuperview the view will be released by the parent view. No need of calling removeFromSuperview, just add it as subview of another view will remove it from it's current parentView.

So use:

for (UIView *view in self.view.subviews)
{
    if (view.tag != 666)
    {
        [self.contentView addSubview:view];
    }
}

According to UIView Class Reference:

addSubview:

Adds a view to the end of the receiver’s list of subviews.

- (void)addSubview:(UIView *)view

Parameters

view

The view to be added. This view is retained by the receiver. After being added, this view appears on top of any other subviews. 

Discussion

This method retains view and sets its next responder to the receiver, which is its new superview.

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 187
Midhun MP Avatar answered Nov 02 '22 23:11

Midhun MP


When you remove your view from superView It will release from memory. So in your case you need to do this:

UINib *infoNib = [UINib nibWithNibName:@"YourXIBFileName" bundle:nil];

NSArray *topLevelObjects = [infoNib instantiateWithOwner:self options:nil];

UIView *infoView = [topLevelObjects objectAtIndex:0];
for (UIView *view in infoView.subviews) {
        [self.contentView addSubview:view];
    }
}
like image 44
Prateek Prem Avatar answered Nov 02 '22 22:11

Prateek Prem