iOS - (instancetype)initWithCoder:(NSCoder *)aDecoder采坑小记
发布日期:2022-04-05 00:52:12 浏览次数:1 分类:博客文章

本文共 2331 字,大约阅读时间需要 7 分钟。

一般我们封装控件时 既要支持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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:ios initWithFrame采坑小记
下一篇:Initializer element is not a compile-time constant

发表评论

最新留言

很好
[***.229.124.182]2024年04月16日 09时45分53秒