Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 598
JoshDG Avatar asked Sep 21 '13 00:09

JoshDG


People also ask

How do I add a custom view to storyboard?

Using a custom view in storyboardsOpen up your story board and drag a View (colored orange below for visibility) from the Object Library into your view controller. Set the view's custom class to your custom view's class. Create an outlet for the custom view in your view controller.


2 Answers

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];
like image 165
ArtSabintsev Avatar answered Oct 15 '22 21:10

ArtSabintsev


This should be simple:

view = [[[NSBundle mainBundle] loadNibNamed:@"MCQView" owner:self options:nil] objectAtIndex:0]
like image 37
Chandu Avatar answered Oct 15 '22 22:10

Chandu