Say that I have a UIView which I would like to re-use in multiple view controllers, given that it is a fairly generic UIView object with high re-usability value (like a UITextField or UISegmentedControl object). From my understanding it would be much easier to reuse this UIView if I wrote the UIView in code, rather than making a XIB using Interface Builder. I have reached this conclusion because if the UIView is written in code then I can simply initialize a new instance of that UIView in any view controller:
MyGreatReusableView *greatReusableView = [[MyGreatReusableView alloc] initWithFrame:CGRectMake(...)];
…and then directly access the properties and attributes of that UIView, just like with the stock UIView controls such as UITextField with it’s .text, .textColor, etc. properties.
However, if I create the UIView as a XIB then it must be tied (through either the File’s Owner or an IBOutlet on the View object in the XIB) to a specific view controller, and therefore can only be used in that view controller. Furthermore, I can only access the properties of controls on the XIB using the IBOutlets which are connected to that view controller.
I am thinking that I have completely misunderstood something with regards to XIB files, as this does seem to be quite a limitation! If someone could provide clarification on whether it is possible to re-use XIB files in multiple view controllers and, if so, provide an example of a code-based solution vs. a XIB-based solution I would be very much appreciative.
Thanks in advance for any assistance!
It is indeed possible to use the same view in multiple view controllers. You were on the right track. The key is that you don’t have to use the view controller to which the view is tied. Here is what I do for re-usable table cells (that contain things like sliders)