从xib初始化的UIView如何继承?

时间:2022-08-26 19:38:44

一、如何从xib自定义一个CustomView

  1)首先创建继承自UIView的子类CustomView

  2)创建名字为CustomView的View的Interface文件

  3)在xib的资源文件中修改class为CustomView

  4)编辑xib,拖拽控件

 

  代码如下:

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activity;

  xib  如下

  从xib初始化的UIView如何继承?

  注意class类型

  从xib初始化的UIView如何继承?

  5)使用这个自定义的view

 

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self test2];

}

- (void)test1
{
    CustomView *v = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0];
    [self.view addSubview:v];
    v.center = self.view.center;
    
    v.activity.backgroundColor = [UIColor redColor];
}

  6)结果

从xib初始化的UIView如何继承?

 

二、如何继承一个从xib初始化的view

  目前还没有这样的方法,苹果已经不推荐使用xib初始化view这样的方式了。

  放弃继承,使用组合的方式来实现

  头文件

@interface MyView : UIView
{
    UIView *view;
    UILabel *l;
}
@property (nonatomic, retain) IBOutlet UIView *view;
@property (nonatomic, retain) IBOutlet UILabel *l;

  实现

#import "MyView.h"
@implementation MyView
@synthesize l, view;

- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Initialization code.
        //
        [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
        [self addSubview:self.view];
    }
    return self;
}

- (void) awakeFromNib
{
    [super awakeFromNib];

    // commenters report the next line causes infinite recursion, so removing it
    // [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
    [self addSubview:self.view];
}

- (void) dealloc
{
     [l release];
     [view release];
     [super dealloc];
}

  参考,https://*.com/questions/5056219/uiview-and-initwithframe-and-a-nib-file-how-can-i-get-the-nib-file-loaded?noredirect=1&lq=1