2
votes

I want to create my own UI library containing several reusable controls. One very simple one could be a LabeledView that will contain a UIView (most probably an UIImageView) and a UILabel below.

----------------
| outer UIView |
| ------------ |
| |          | |
| |  UIView  | |
| |          | |
| ------------ |
| | UILabel  | |
| ------------ |
----------------

How can I implement this in Interface Builder and "inject" the inner UIView and UILabel when creating the outer UIView? I have the outer UIView as File's Owner and the inner UIView and the UILabel connected with IBOutlets to properties in my LabeledView. I am now imagining an init function like:

[[LabeledView alloc] initWithView:(UIView *)theView andLabel:(UILabel *)theLabel]

That method should load the View from the nib with its defined layout and insert theView and theLabel into it. This couldn't be to hard, no? I don't get it...

2

2 Answers

1
votes

If you've defined the views etc in a nib then you can add them at runtime using loadNibNamed: described here : http://developer.apple.com/library/ios/documentation/uikit/reference/NSBundle_UIKitAdditions/Introduction/Introduction.html

This returns an array, the first object will be the top level object in the nib - your container view in the example above.

You dont use alloc/init when loading things from a nib, because the nib itself contains a serialised version of the object, which is already instantiated.

0
votes

This might help you, to create independent UIView subclass with their own IBOutlet, and methods. Also they will be independent of `File's Owner", means you can use them anywhere in your code.

Follow these steps

  • Leave the File's Owner field empty.
  • Click on actual view in xib file of your CustomView and set its Custom Class as CustomView (name of your custom view class)
  • Add IBOutlet in .h file of your custom view.
  • In .xib file of your custom view, click on view and go in Connection Inspector. Here you will all your IBOutlets which you define in .h file
  • Connect them with their respective view.

  • In .m file of your CustomView class, override the init method as follow

    -(CustomView *) init{ CustomView result = nil; NSArray elements = [[NSBundle mainBundle] loadNibNamed: NSStringFromClass([self class]) owner:self options: nil]; for (id anObject in elements) { if ([anObject isKindOfClass:[self class]]) { result = anObject; break; } } return result; }

  • Now when you want to load your CustomView, use the following line of code [[CustomView alloc] init];