重寫時候, 默認走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)用順序