dmaestro12
dmaestro12

Reputation: 903

How to get multiple copies of a UIView loaded from a nib?

I want to use a UIView hierarchy multiple times (the nib object is a template). Unfortunately, UIView does not conform to <NSCopying> so

[cell.contentView addSubview: [[templEditCellView copy] autorelease]];

does not work.

I wasn't surprised, since I want a deep copy of the view hierarchy.

Currently the view is one of several top-level objects in the nib it is loaded from. Is there a way to reload a single specified top-level object from the nib? Should I split out the view to a single NIB which can be reloaded on demand? Or is there another way to make a deep copy of a view?

Thanks!

Upvotes: 3

Views: 5990

Answers (3)

NSResponder
NSResponder

Reputation: 16861

Easiest way to make a deep copy of a view is to archive and unarchive it.

id copyOfAView = 
  [NSUnarchiver unarchiveObjectWithData:
    [NSArchiver archivedDataWithRootObject:aView]]; 

Putting the view in its own nib works too. You can create an NSNib object and reload it as many times as you want.

Upvotes: 7

dmaestro12
dmaestro12

Reputation: 903

This seems to be working well at the moment for what I need:

if (! templEditCellView) {
  [[NSBundle mainBundle] loadNibNamed:@"TextEditCellView" owner:self options:nil];
  if (! templEditCellView) {
    abort(); // !!
  }
}
[cell.contentView addSubview: templEditCellView];
templEditCellView = nil;

The table controller is placing the same customized view heirarchy in the content of each cell in this case.

I'd love to see an approach that doesn't multiply nib files if I have lots of different cell customizations (as I might).

Upvotes: 1

Felixyz
Felixyz

Reputation: 19143

You can't load it directly to the cell's content view, but you can create a class with outlets for the view(s) and load it with

[[NSBundle mainBundle] loadNibNamed:@"TheNib" owner:anObject options:nil];

There is more info around SO and the 'net about loading table view cells from nibs. I really like Bill Dudney's approach but the method described by Jeff LaMarche is easier and great for many situations.

Upvotes: 2

Related Questions