美文网首页iOSiOSiOS 进阶
加载view的两种方式 -- 代码 + xib

加载view的两种方式 -- 代码 + xib

作者: 崠崠 | 来源:发表于2017-12-19 14:10 被阅读1103次

在项目中经常会将一个复杂的页面分为多个页面加载显示,区分逻辑的同时避免臃肿。在这里记录一下。

1、代码加载

代码加载的方式对于view模块分块加载方便简单多了,也有利于团队的协作和维护

@interface ViewWithoutXib : UIView

//类方法加载 -- 初始化方法在其中
+(instancetype)initWithFrame:(CGRect)frame withTitle:(NSString *)title;

@end
@interface ViewWithoutXib()

@property (nonatomic , strong) UILabel * titleLB;

@end

@implementation ViewWithoutXib

+(instancetype)initWithFrame:(CGRect)frame withTitle:(NSString *)title{
    return [[self alloc] initWithFrame:frame withTitle:title];
}

//初始化
-(instancetype)initWithFrame:(CGRect)frame withTitle:(NSString *)title{
    self = [super initWithFrame:frame];
    if (self) {
        [self initView:title];
    }
    return self;
}
//加载控件
-(void)initView:(NSString *)title{
    self.backgroundColor = [UIColor yellowColor];
    self.titleLB.text = title;
}


#pragma getter and setter

-(UILabel *)titleLB{
    if (_titleLB == nil) {
        _titleLB = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.frame.size.width - 20, self.frame.size.height)];
        [self addSubview:_titleLB];
    }
    return _titleLB;
}

2、xib加载

xib加载相对而言,在构建页面上比较方便,做起来比较块,但是对应的注意的点也比较多。

  1. 新建UIView,Xcode新建UIView不能同时关联xib ,需要自己再新建xib文件进行关联


    新建View.jpg
  2. xib界面File's owner处为空(不同于ViewController),customClass的class处填写view的类名


    File's owner.jpg
    Class.jpg

2018.06.12新增
设置 frame大小时,实际运行时发现高度没有固定,是Autoresizing的设置问题(纵向设置不需要设置)


Autoresizing.png
  1. 初始化
    加载xib文件,进行关联
- (nullable NSArray *)loadNibNamed:(NSString *)name owner:(nullable id)owner options:(nullable NSDictionary *)options;

控件加载

@interface ViewWithXib : UIView

+(instancetype)initWithXib:(CGRect)frame withTile:(NSString *)title;

@end
@implementation ViewWithXib

+(instancetype)initWithXib:(CGRect)frame withTile:(NSString *)title{
    ViewWithXib *view = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil].lastObject;
    view.frame = frame;
    view.title = title;
    [view awakeFromNib];

    return view;
}

//1、正在准备初始化 -- loadNibName 之后会调用
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        
    }
    return self;
}
//2、初始化完毕`(若想初始化时做点事情,最好在这个方法里面实现)`
- (void)awakeFromNib {
    [super awakeFromNib];
    
     self.titleLB.text = self.title;
}

@end

运行结果


结果.png

虽然简单,但还是在这里记录一下。

相关文章

网友评论

    本文标题:加载view的两种方式 -- 代码 + xib

    本文链接:https://www.haomeiwen.com/subject/kvunixtx.html