jowie
jowie

Reputation: 8068

How can I wire up IBOutlets to a custom UIView?

I have a view controller with generic interface elements that needs to load in a menu view. I have created a custom UIView called MenuView.h and MenuView.m and built all the views in it using code. However, I'd much rather set out the views in a .xib file so that I can lay them out more easily.

I do know about the whole loadNibNamed in order to load a nib/xib file into my custom UIView, however what I don't understand is how I can wire up some IBOutlets to the loaded nib.

Does anyone have any pointers to how this is done please?

Upvotes: 2

Views: 2502

Answers (1)

Rakesh
Rakesh

Reputation: 3399

To do this:

  1. Create xib.
  2. Set the file's owner as the class you want to act as a controller (usually a UIViewContoller subclass -although before iOs5, Apple doesn't recommend using UIViewController when having multiple controllers on screen). (This step is to make this class visible in the xib so that you can create your outlets).
  3. Create the IBOutlet/IBAction for your custom view in this class.
  4. And when calling loadNibNamed:owner:option: , give the owner as an object for this class.

i.e

UIView *view = [[[NSBundle mainBundle] loadNibNamed:@"CustomXib" owner:<customClassobject> option:nil] objectAtIndex:0];

and to use it somewhere:

[someView addSubview:view]

Another way would be to create a custom view controller and use the view controller to access the view .

  • Repeat steps 1-3 as above keeping the custom view controller(say MyViewCon) as the file's owner.You will also have to connect the view reference of the controller to the xib view.

Then instead of using loadNibNamed... , initialize the view controller. i.e

MyViewCon *myVC = [[MyViewCon alloc] initWithNibName:@"CustomXib"];

then wherever you have to use the view use myVC.view. For eg,

 [someview addSubview: myVC.view];

UPDATE:

If you are using the same UIViewController subclass as the file's owner for the child and parent view, you should realize that it will be two different objects of the same class and might cause confusion since the same variable might show different values when performing actions in the same scene.

For more information from a design point of view regarding multiple controllers for a scene refer here.

Upvotes: 3

Related Questions