iOS - (instancetype)initWithCoder:(NSCoder *)aDecoder采坑小记

时间:2019-09-19
本文章向大家介绍iOS - (instancetype)initWithCoder:(NSCoder *)aDecoder采坑小记,主要包括iOS - (instancetype)initWithCoder:(NSCoder *)aDecoder采坑小记使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一般我们封装控件时 既要支持xib 又要支持手码 一般我们会在以下两个方法里执行我们的自定义操作。然后关于initWithCoder的小坑来了。

/// 手码
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //  自定义操作
        [self initData];
        [self initUI];
    }
    return self;
}

/// xib
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
   self = [super initWithCoder:aDecoder];
    if (self) {
        //  自定义操作
        [self initData];
        [self initUI];
    }
    return self;
}

我是在view上包装了一个 UITableView

- (void)initUI {
    self.backgroundColor = [UIColor clearColor];
    [self addSubview:self.appendixTableView];
    [self.appendixTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top);
        make.left.equalTo(self.mas_left);
        make.bottom.equalTo(self.mas_bottom);
        make.right.equalTo(self.mas_right);
    }];
    
    [self.appendixTableView registerClass:[iComeAppendixTableViewCell class] forCellReuseIdentifier:iComeAppendixTableViewCellReused];
    
}

- (UITableView *)appendixTableView {
    if (!_appendixTableView) {
        _appendixTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _appendixTableView.delegate = self;
        _appendixTableView.dataSource = self;
        _appendixTableView.backgroundColor = [UIColor clearColor];
        _appendixTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _appendixTableView.bounces = NO;
        _appendixTableView.showsHorizontalScrollIndicator = NO;
        _appendixTableView.showsVerticalScrollIndicator = NO;
        
        if (@available(iOS 11.0, *)) {
            _appendixTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
           
        }else{
            self.viewController.automaticallyAdjustsScrollViewInsets = NO;
        }
        
    }
    return _appendixTableView;
}

然后发现设置的tableview的某些属性不起作用,比如背景色、分割线、等。各种方法试验过后发现问题在这里

// 包装UITableView会有问题 包装UICollectionView不会有问题
//- (instancetype)initWithCoder:(NSCoder *)aDecoder {
//    self = [super initWithCoder:aDecoder];
//    if (self) {
//        [self initData];
//        [self initUI];
//    }
//    return self;
//}

// 在awakeFromNib方法中不会有问题
- (void)awakeFromNib {
    [super awakeFromNib];
    [self initData];
    [self initUI];
}

综上所述:

initWithCoder 包装UITableView会有问题 所以最好都在awakeFromNib中添加自定义操作

原文地址:https://www.cnblogs.com/lijianyi/p/11549875.html