首页 > 代码库 > loadNibNamed:(NSString *)name owner:(nullable id)owner options:(nullable NSDictionary *)options用法

loadNibNamed:(NSString *)name owner:(nullable id)owner options:(nullable NSDictionary *)options用法

1.name xib的名字 owner当前类对象 options初始参数

实际应用:

NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"***" owner:self options:nil];

  nibs[0]是当前view的对象  nibs[1]当前view的背景 ,我们可以在init中对当前frame以及当前view的背景的frame进行赋值, nibs[1]的背景是半透明的,如果当前的xib是View,把view添加到父对象的时候nibs[1]没有添加到父空间,则当前的view是全透明的,

举个例子:这个是我创建的xib

技术分享

 

 

该xib对应的initWith

-(instancetype)initWithCancleButtonTitle:(NSString *)cancelTitle otherButtonTitle:(NSString *)otherTitle
{
    CGRect frame = CGRectMake(0, 0, Main_Screen_Width-40, 180);
    self = [super initWithFrame:frame];
    if (self) {
        
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"***" owner:self options:nil];
        self = nibs[0];
        self.frame = CGRectMake(0, 0, Main_Screen_Width-40, 180);

        coverView = nibs[1];
        [self setUIController];

        if (rect.size.height > 54) {
            self.frame = CGRectMake(0, 0, Main_Screen_Width-40, 180);
        }
        [self.cancleButton setTitle:cancelTitle forState:UIControlStateNormal];
        [self.otherButton setTitle:otherTitle forState:UIControlStateNormal];
    }
    return self;
}
-(void)setUIController{
    coverView.frame = CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height);
    coverView.backgroundColor = [UIColor redColor];
    self.layer.cornerRadius = 4.0;
    self.layer.masksToBounds = YES;
    [self.cancleButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.otherButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    _line1.backgroundColor = [UIColor grayColor];
    _line2.backgroundColor = [UIColor grayColor];
}

 把当前view添加到window上:

UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.center = CGPointMake(Main_Screen_Width/2, Main_Screen_Height/2);
    [window addSubview:coverView];
    
    
    [window addSubview:self];

 技术分享

红色的view是半透明的,如果 [window addSubview:coverView];去掉的效果

技术分享

 

loadNibNamed:(NSString *)name owner:(nullable id)owner options:(nullable NSDictionary *)options用法