ios拓展4-自定義tableViewcell以及注意點

重寫時候, 默認走initWithStyle: 如果想通過 init 方法創(chuàng)建,需要[[YYOrderCell alloc] init]
(ps: 如果通過initWithStyle或者registerClass=======>不會走 init 進行初始化  )
//   cell 初始化方法
YYOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[YYOrderCell alloc] init];
    }
//自定義cell
#import "YYOrderCell.h"

@implementation YYOrderCell

- (instancetype)init{
    if (self = [super init]) {

        [self setupUI];// ========= 必須=======放在這個位置===
        NSLog(@"1");
    }
    return self;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    NSLog(@"2");
/*=============*/
    //[self setupUI];// ========== 如果=====放在這個位置==>無效
    return [super initWithStyle:style reuseIdentifier:reuseIdentifier];
/*=============*/

/*======下面這種模式有效=======*/
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self) {
        [self setupUI];
    }
    //不能采用return super模式
    
    return self;
}

- (void)setupUI{
    
    UIImageView *pic = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
    pic.backgroundColor = [UIColor yellowColor];
    
    UITextView *viewtext = [[UITextView alloc] initWithFrame:CGRectMake(200, 10, 100, 100)];
    viewtext.backgroundColor = [UIColor grayColor];
    
    self.backgroundColor = [UIColor blueColor];
    self.contentView.backgroundColor = [UIColor redColor];
    
    // contentView 和 直接添加到cell的區(qū)別

    [self.contentView addSubview:pic];
    [self addSubview:viewtext];
    
    
}
@end
init和initWithStyle調(diào)用順序
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容