Load view from NIB file from several different UIViewControllers

家住魔仙堡 提交于 2020-01-01 20:03:43

问题


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.


回答1:


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>.



回答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.




回答3:


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.



来源:https://stackoverflow.com/questions/3524051/load-view-from-nib-file-from-several-different-uiviewcontrollers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!