How could I clone/duplicate some sort of UIView for iOS?

ios, objective-c, uiview, xcode

Solution

This is a very natural and useful thing to do. What you're looking for is a container view controller. Put your reusable "cell" into its own view controller and its own nib file. Then, in your parent view controller, use `addChildViewController:` to add as many of these as you'd like and configure each of them. They can each have their own IBOutlets that you can use to modify the contents.

This is very similar to the pattern used by `UITableView` and `UITableViewCell` (it doesn't use "child view controllers" specifically, but it does use this pattern).

For full details, see "Creating Custom Container View Controllers" in the View Controller Programming Guide for iOS.

Note that Storyboard includes a "Container View" as an option in the object templates to make this even easier.

If you want lower-level access, you can also do this by hand using `UINib` to load the nib file and wire its outlets (and this is how we used to do it before iOS 5), but today I would use child view controllers.

Problem

(screenshot below helps explain what I am trying to do) The idea behind this is that I have a `UIView`, with various different `UI` elements inside, for example, let's say I have a `UIView`, and inside there we have a `UILabel`. Now I'm wanting to duplicate the `UIView` (with the label inside) BUT somehow after that I need to perhaps make a change to the label, e.g. change the text property. The reason I need something like this is so I can structure the `UIView` with everything I need in it looking nice, but to actually have different data with different copies of it. I'm not certain this is the best approach, but it's the only one I could come up with. If anyone has any ideas on how to do this, or any ideas on a better approach I'd really appreciate it. A lot!

Original source