加載 xib 文件 UIView


 

直接使用: 😁

-(id)initWithFrame:(CGRect)frame {
    self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
                                          owner:self
                                        options:nil] objectAtIndex:0];
    self.frame = frame;
    return self;
}

 

加載 UIView 的 xib 文件方式有以下幾種方式:

一 .直接加載 xib 文件, 沒有.h.m 文件

1. NSBundle 方式

  NSArray *objs = [[NSBundle mainBundle]loadNibNamed:@"XibView" owner:nil options:nil];

    UIView *xibView = objs[0];

    xibView.backgroundColor = [UIColor redColor];

    [self.view addSubview:xibView];

 

2. UINib

//一個nib 對象就代表一個 xib 文件

 

 

    //UINib *nib = [UINib nibWithNibName:@"XibView" bundle:[NSBundle mainBundle]];

 

    //一般 bundle nil,默認就是 mainbundle

 

    UINib *nib = [UINib nibWithNibName:@"XibView" bundle:nil];

 

    NSArray *objs = [nib instantiateWithOwner:nil options:nil];

 

    [self.view addSubview:objs[0]];

 

二. 需要.h .m 文件, 並連線

 

方式一.  只使用一個 xib

 

參考: http://www.jianshu.com/p/639fd5f79837

步驟:

1.新建一個view 繼承 UIView,命名:XibView

2.新建一個 xib 文件,命名:XibView

3.在 xib 文件中,點擊 view(不是設置File's owner), 然后設置右側Class 選擇為 XibView

//此時就可以拖動 xib 中的控件到 XibView的.h 中了

4.外部使用該 view

   NSArray *objs = [[NSBundle mainBundle]loadNibNamed:@"XibView" owner:nil options:nil];

    XibView *view = objs.firstObject;   

    [self.view addSubview:view];

  

方式二. 在一個 xib 中使用另一xib  OtherView文件

參考: http://www.jianshu.com/p/9e45590126e4

 

1.同上 OtherView

2.同上 OtherView

3.在 xib 文件中,點擊File owner, 選擇右側Class 為 OtherView, 注意此時不是點擊 view

4.將 xib view 拖拽到OtherView的. h文件中

5..被使用的OtherView需要初始化

 // initWithCoder為 xib 文件的入口

- (instancetype)initWithCoder:(NSCoder *)coder

{

    self = [super initWithCoder:coder];

    if (self) {

        [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];

        [self addSubview:self.view];

    }

    return self;

}

 

- (void)layoutSubviews {

    [super layoutSubviews];

    

    self.view.frame = self.bounds;

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM