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?
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.
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.
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];
This should be simple:
view = [[[NSBundle mainBundle] loadNibNamed:@"MCQView" owner:self options:nil] objectAtIndex:0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With