JoshDG
JoshDG

Reputation: 3931

iOS: Custom view with xib

I'm missing something important. Not exactly sure what it is.

I have a custom view subclass. I created a xib file to design its layout. I connected four buttons as outlets to the class.

#import <UIKit/UIKit.h>

@interface MCQView : UIView
@property (strong, nonatomic) IBOutlet UIButton *btn1;
@property (strong, nonatomic) IBOutlet UIButton *btn2;
@property (strong, nonatomic) IBOutlet UIButton *btn3;
@property (strong, nonatomic) IBOutlet UIButton *btn4;

I then have

#import "MCQView.h"

@implementation MCQView
@synthesize btn1,btn2,btn3,btn4;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"MCQView" owner:self options:nil] objectAtIndex:0]];
            NSLog(@"%@", btn1);

    return self;
}

I then add the view to another view controller via: initWithFrame.

When I try to log btn1, to see if it exists, it prints null. I assume that its because I haven't initialized it, but I'm not exactly sure how to do that, considering that if I create it as a new button then all of the stuff in the xib will be useless?

Upvotes: 12

Views: 17217

Answers (4)

Motoko
Motoko

Reputation: 1132

For Swift (2):

    var nib = NSBundle.mainBundle().loadNibNamed("MCQView", owner: self, options: nil)
    view : MCQView = nib[0] as! MCQView
    self.view.addSubview(view)

Upvotes: 1

Chandu
Chandu

Reputation: 630

This should be simple:

view = [[[NSBundle mainBundle] loadNibNamed:@"MCQView" owner:self options:nil] objectAtIndex:0]

Upvotes: 4

ArtSabintsev
ArtSabintsev

Reputation: 5200

Edited Response:

Oh wait, you're trying to initialize the view within your class? Don't do that.

In Interface Builder, set the Class of MCQview.xib in to MCQView to automatically create the connection. The, connect all your buttons, if you haven't already.

Afterwards, you'll be able to edit the properties automatically as you see fit.

enter image description here

Original Response

I'm doing this from memory, but I think you it should be done like this:

NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MCQView" owner:self options:nil];

UIView *view = [[UIView alloc] init]; // or if it exists, MCQView *view = [[MCQView alloc] init];

view = (UIView *)[nib objectAtIndex:0]; // or if it exists, (MCQView *)[nib objectAtIndex:0];

[self.view addSubview:view];

Upvotes: 13

Dan Loughney
Dan Loughney

Reputation: 4677

You are right that you don't need to init the buttons with the XIB. Try using initWithNibName instead of loadNibNamed.

Upvotes: 0

Related Questions