0

I have been loading view from Nib files successfully using the approach found on this site

[[NSBundle mainBundle] loadNibNamed:@"YourNibName" owner:self options:nil];

The problem is that, because we have to set the File Owner, this nib file becomes "attached" to this view controller. This view is subclass of UITableViewCell and I wanted to load this nib file from several different vc's. Thanks for your help.

Community
  • 1
  • 1
Paulo Casaretto
  • 967
  • 10
  • 33

3 Answers3

2

A nib is just a template, you can load it over and over again.

If using iOS4, you might want do look at UINib which gives improved performance for repeated nib loading.

Eiko
  • 25,601
  • 15
  • 56
  • 71
0

I'll present two options:

  • Create a class NibLoader with a single @property (nonatomic, retain) IBOutlet id mainObject; and a method called loadNibNamed:bundle:). Then, do MyView * v = [[NibLoader loadNibNamed:"MyView" bundle:nil] mainObject];. (A GCC 4.0 property access bug meant that [...].mainObject would call [...] twice; it's been fixed in 4.2.)
  • Create @protocol MyNibOwner which has @property (nonatomic, retain) IBOutlet MyView * myView;, and change the file's owner class to id<MyNibLoader> or NSObject<MyNibLoader>.
tc.
  • 33,468
  • 5
  • 78
  • 96
  • or `UIViewController`, but that stops views from loading your nib as a subview in init. – tc. Aug 19 '10 at 19:13
  • The second solution sounds perfect, but IB does not accept the protocol after id. Setting it to id and keeping the "broken" reference worked but I suppose its not very safe. – Paulo Casaretto Aug 19 '10 at 23:45
  • That's odd, since `IBOutlet id delegate` works perfectly fine (but perhaps it just ignores the protocol in that case; it wouldn't surprise me). You could add a dummy `@interface MyNibOwnerHack:NSObject` for InterfaceBuilder's benefit. – tc. Aug 20 '10 at 16:25
  • 1
    shameless plug: I have just posted a nice addition to this method that proved very helpful to me on http://loudcoding.com/posts/add-a-category-to-a-custom-uitableviewcell-when-loading-from-a-nib-file/ – Paulo Casaretto Mar 30 '12 at 01:23
  • 1
    @PauloCasaretto: You probably don't want to do `[self viewWithTag:0]`, since IIRC 0 is the default tag. You also need to be *slightly* careful when reusing tag IDs. – tc. Apr 04 '12 at 14:39
-1

Pedantically, a nib should probably have a single controller. What I would probably do is create a new UIViewController subclass that controls the stuff in this nib of yours, and then whenever you want the stuff in the nib, create one of these view controllers and ask it for the stuff, instead of loading the nib directly.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • Ugh, no. Embedding view controllers in view controllers is icky, and if you just want the view, you need to do `UIView * v = [[vc.view retain] autorelease]; vc.view = nil; return v;` or things would behave strangely (I forgot what the bug is or which OS version). – tc. Aug 19 '10 at 19:03