Add same subview multiple times to view

2019-03-10 01:26发布

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.

1条回答
劫难
2楼-- · 2019-03-10 02:00

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.

查看更多
登录 后发表回答