One xib File with Multiple “File's Owner”s

爷,独闯天下 提交于 2019-11-30 04:43:23
Jonah

A nib's File's Owner is not strictly enforced. Instead it is only used to determine available outlets and actions, and to set bindings within Interface Builder. You can load a nib with any object as its File's Owner regardless of the class set in the nib file. When a nib is loaded it will send messages to the File's Owner to re-establish bindings. If the actual File's Owner object does not recognize those selectors you will have triggered an "unrecognized selector" exception. This means that if your nib binds some UITableViewCell to the 'cell' outlet of its File's Owner then any object with a 'cell' property could load that nib. You just need to be careful not to use this behavior to send an unrecognized selector or unexpected outlet class.

In your case, consider creating a single UIViewController subclass to act as the File's Owner of your nib. Have each of your three existing controllers extend that view controller subclass. That way they can all inherit the same set of properties expected by the nib file and all safely load that nib while still defining their own custom behavior.

albertamg

The checked answer to this question discusses two approaches to load custom table cells from nib files that do not require to set the File's Owner to your specific controller. These approaches let you reuse cells with different owners.

A "shared" super class as a file owner is not always a good solution. Remember that you can always load the xib in your view, and make connections without using outlet, for example:

UIView *aView = [[NSBundle mainBundle] loadNibNamed:@"MyXibFile" owner:self options:nil]
//Search subviews by tag. Obviously you need to set the tag on your view in MyXibFile
UILabel *aLabel = (UILabel*)[aView viewWithTag:996]; 
UILabel *aTextField = (UITextField*)[aView viewWithTag:997]; 
aTextField.delegate = self;
//etc...

I can't say that this is a clean solution, but in some cases could work better than inheritance .

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