iOS xibView的理解

xib的运用

引言: xibView 很好用, 节省很大的时间去写UI, 我们可以把更多的精力去写业务获取其他内容, 而不应该把大把的时间花在创建UI上面.
xib:主要有动画,和拉约束, 相对于代码来说的难点. 其他我觉得都比较好.

.h 文件


@interface MDJPayView : UIView

@property (nonatomic, weak) UIView *supV;

+ (instancetype)mzy_xibView; // 为什么用这个 

- (void)configDefaultConstraints;

- (void)show;

- (void)dismiss;

@end

.m 文件

import "MDJPayView.h"
#import "Masonry.h"

#define kScreenH ([[UIScreen mainScreen]bounds].size.height)
#define kScreenW ([[UIScreen mainScreen]bounds].size.width)

@interface MDJPayView ()

@property (weak, nonatomic) IBOutlet UIButton *bgBtn;

@property (weak, nonatomic) IBOutlet UIView *mainView;

@end

@implementation MDJPayView

- (void)dealloc {
    
    NSLog(@"-------MDJPayView 释放--------");
}


// 这个方法少用
- (instancetype) initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        NSLog(@"----initWithFrame-----");
        self = [[[NSBundle mainBundle] loadNibNamed:@"MDJPayView" owner:nil options:nil]firstObject];
        self.frame = frame;
    }
    return self;
}

// 这个方法多用 因为看 dealloc 打印你就知道了
+ (instancetype)mzy_xibView
{
    return [[[NSBundle mainBundle] loadNibNamed:@"MDJPayView" owner:nil options:nil]firstObject];
}


- (void)configDefaultConstraints {
    
    self.mainView.frame = CGRectMake(0, kScreenH, kScreenW, 20);
}


- (void)show {
    
    if (self.supV) {
        [self.supV addSubview:self];
    }
    else {
        [[UIApplication sharedApplication].keyWindow addSubview:self];
    }
    
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.superview).insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    
    self.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.f];
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.3f];
        self.mainView.frame = CGRectMake(0, kScreenH - 400, kScreenW, 400);
        
    } completion:^(BOOL finished) {
        
    }];
     
}

- (void)dismiss {
   
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.f];
        self.mainView.frame = CGRectMake(0, kScreenH, kScreenW, 400);
        [self.mainView layoutIfNeeded];
    
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (IBAction)bgBtnAction:(id)sender {
    
    [self dismiss];
}

@end

试图控制器掉用

   MDJPayView *payView = [MDJPayView mzy_xibView];
    
    payView.supV = self.view;

    [payView configDefaultConstraints];

    [payView show];
    
    

你可能感兴趣的:(iOS xibView的理解)