iOS:使用xib的自定义视图

Jos*_*hDG 12 cocoa-touch ios

我错过了一些重要的事情.不完全确定它是什么.

我有一个自定义视图子类.我创建了一个xib文件来设计它的布局.我将四个按钮连接到班级.

#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;
Run Code Online (Sandbox Code Playgroud)

然后我有

#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;
}
Run Code Online (Sandbox Code Playgroud)

然后,我通过视图添加到另一个视图控制器:initWithFrame.

当我尝试记录btn1时,为了查看它是否存在,它会输出null.我认为它是因为我没有初始化它,但我不确定如何做到这一点,考虑到如果我将它创建为一个新按钮,那么xib中的所有东西都将是无用的?

Art*_*sev 13

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];
Run Code Online (Sandbox Code Playgroud)