VansFannel
VansFannel

Reputation: 45911

Connect a new xib to a class that inherits from UIView

I'm developing an iOS app with latest SDK.

I want to create a custom UIView and set layout using a XIB file.

To this XIB, I have added four UIButtons using Interface Builder.

Now I want to connect these four buttons to my custom UIView class and manage there IBActions. This is very important, I have to do it this way.

To load the xib I do:

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder]))
    {
        [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"MyCustomView"
                                                        owner:self
                                                      options:nil] objectAtIndex:0]];
    }
    return self;
}

I also have a storyboard and I have added an UIView to main ViewController using Interface Builder.

My question is: What do I have to do to connect the new XIB file to my custom UIView on Interface Builder?

I think I have to open this new xib on Interface Builder and set main ViewController as File's Owner, and set my custom UIView class as class for the view on this new XIB, but I'm not sure.

And, on main ViewController change the class for this new view to my custom UIView.

Upvotes: 0

Views: 4160

Answers (2)

Zen
Zen

Reputation: 3117

In Interface Builder, set the custom class to your CustomView.Make the connections to this custom class. In the whichever view controller you want to use this xib, Simply load the nib using loadNibNamed:owner:options: method.

CustomView *cView = [[[NSBundle mainBundle] loadNibNamed:@"CustomView"
                                                    owner:nil
                                                  options:nil] objectAtIndex:0];
[cView.button1 addTarget:self action:@selector(actnForBtn1:) forControlEvents:UIControlEventTouchUpInside];
[cView.label1 setText:@"sometext"];
[self.view addSubview:cView];

And do add the method actnForBtn1:(id)sender in your view controller to do different things in different view controllers.

Upvotes: 1

btype
btype

Reputation: 1576

In View.h

+(View *)loadViewFromNib;

In View.m

+(View *)loadViewFromNib{
    return (View *)[[[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:0] objectAtIndex:0];
}

To load the View call

View *view = [View loadViewFromNib];

In your View.xib file set the Files Owner class to View and your Views class to View connect the Outlets only to the View, not to the FilesOwner!

Upvotes: 0

Related Questions