So I have this view that I design in a storyboard view controller and I want to reuse that design more than once from code. Is that possible to do in XCode 5? If so can you please show me the right direction?
Asked
Active
Viewed 1,129 times
2 Answers
2
Cheap way, give the view a tag.
then UIView *view = [UIView viewWithTag:tag];
and then go ahead and copy it, add it to the view.
Or try this:
id copyOfView = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];
Bear in mind that not everything necessarily gets archived and unarchived correctly (custom fonts, layer settings like corner radius) and IBOutlets should be steered clear of as they don't get updated on the cloned objects.

CMash
- 1,987
- 22
- 35

Schemetrical
- 5,506
- 2
- 26
- 43
-
1Well as far as I know `UIView` does not implement `NSCopying` protocol so something like `[view copy]` will not work. Any idea how to copy a view without me having to create a method that does that? – Mihai Fratu Aug 22 '14 at 15:53
-
1@MihaiFratu try this: `id copyOfView = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];` – Schemetrical Aug 23 '14 at 02:03
-
Archiving the view... that's... interesting! It works.. probably isn't too poor on performance... seems to have some bugs though as one of my buttons in the view lost its custom font and corner radius. It seems a bit lazy and really you should potentially do something like moving the view into a nib and instantiating it multiple times rather than cloning it. – CMash Sep 23 '16 at 15:49
-
Actually it's probably a really bad idea.. I had an IBOutlet on the view I was duplicating and just spent ages trying to figure out why the functions I was calling on that IBOutlet object were having no effect. It's because the IBOutlet was still pointing to the original view's object rather than the newly created one... – CMash Sep 23 '16 at 16:21
-
@CMash Yup, you gotta redo some selectors. – Schemetrical Oct 12 '16 at 00:09
0
What you are actually asking is how to implement view controller polymorphism.
This is a common object oriented programming design pattern / principle.
As defined on Wikipedia.
You may find this SO Q&A helpful.
Essentially you want to set certain destination view controller public properties by the implementation of the prepareForSegue
method in the parent view controller.

Community
- 1
- 1

andrewbuilder
- 3,629
- 2
- 24
- 46
-
Hm... I think you miss understood my question. All I want to do is duplicate a view that was designed using the InterfaceBuilder and it's part of a given view controller. Something like a table view cell is reused in a table view... – Mihai Fratu Aug 22 '14 at 15:55