Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add same subview multiple times to view

I don't know if this is possible, but what I would like to do is add a subview several times to the view. I have tried something like this:

[self.view addSubview: newView];
newView.center = CGPointMake(160, 100);
[self.view addSubview: newView];
newView.center = CGPointMake(160, 200);
[self.view addSubview: newView];

All this does is move newView around, without adding new ones. Any ideas?

I also tried this:

[self.view addSubview:newView];
UIView *anotherView = newView;
anotherView.center = CGPointMake(160, 100)
[self.view addSubview:anotherView];

Edit

Here's a solution I've learned with time

Another way to solve the problem would be to make a separate nib containing the view and add instances of the nib several times. A good template to work off to implement this solution is to do it the same way a custom UITableViewCell is used in the cellForRowAtIndexPath method.

like image 743
coder Avatar asked Sep 30 '11 19:09

coder


1 Answers

A view can only be contained in a single parent view's hierarchy. As soon as you add it to a new one, it is removed from the previous one. In this case, it is being removed and added back to the same view's hierarchy. You would need to make a copy of the sub-view to have it appear multiple times.

like image 60
Christopher A Avatar answered Nov 16 '22 20:11

Christopher A