美文网首页程序员iOS学习笔记iOS OC 学习手册
ios拓展4-自定义tableViewcell以及注意点

ios拓展4-自定义tableViewcell以及注意点

作者: Abler | 来源:发表于2016-07-12 16:46 被阅读275次
重写时候, 默认走initWithStyle: 如果想通过 init 方法创建,需要[[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的区别

    [self.contentView addSubview:pic];
    [self addSubview:viewtext];
    
    
}
@end
init和initWithStyle调用顺序

相关文章

网友评论

    本文标题:ios拓展4-自定义tableViewcell以及注意点

    本文链接:https://www.haomeiwen.com/subject/bizrjttx.html