-->

Make a deep copy of a UIView and all its subviews

2020-07-22 19:25发布

问题:

I need to make a deep copy of a UIView containing several subviews. Please help me figure out how to do this? I've done some searching on google and SO and not found anything that does what I want.

Explanation for those who would like to know why: I have an infinitely scrolling UIScrollView where, of course, the contents repeat. Each 'set' of the contents (for example, say 26 UIButtons labeled A-Z) is contained inside one view. This is the view I need to make a deep copy of, so that I can display multiple instances of it onscreen within the scrollview.

I cannot simply recreate the structure of the view containing the buttons, because pressing the buttons calls a function of a class that my UIScrollView subclass does not have access to. Nor would I wish to recreate them, because it seems a waste to go through the logic to recreate and place all subviews in the container view when I could simply make a deep copy instead.

Can anyone help me?

回答1:

(Posted from my comment on request)

Aha right I see now. I think the only way would be to create more copies at runtime and hide them; else you'd have to iterate through all subviews, re-create all frames, colors etc... but as you say you'd then likely run into issues copying button targets etc - but there might be something useful to help accomplish that here:

How to get UIButton Target, Action and Control events?