您的位置:首页 > 产品设计 > UI/UE

纯代码实现自定义UITableView的cell

2016-05-04 17:03 561 查看

纯代码实现自定义UITableView的cell

新建一个继承自UITableViewCell的类

重写initWithStyle:reuseIdentifier:方法,在里面实现:

添加所有需要显示的子控件(不需要设置子控件的数据和frame,子控件要添加到contentView中)

进行子控件一次性的属性设置(有些属性只需要设置一次, 比如字体\固定的图片)

BNPSettingCell.h文件:

/*本代码实现自定义cell的分隔线*/
#import <UIKit/UIKit.h>

@interface BNPSettingCell : UITableViewCell

/****这个位置可以定义一些需要的属性,方便外界传值****/
//往外界提供一个类方法,以便获取自定义的cell
+ (instancetype)cellWithTableView:(UITableView *)tableView;

@end


BNPSettingCell.m文件:

#import "BNPSettingCell.h"

@interface BNPSettingCell ()
@property (nonatomic,strong)UIView *viewLine;
@end

@implementation BNPSettingCell

+ (instancetype)cellWithTableView:(UITableView *)tableView{

static NSString *ID = @"setting";
//先从缓存池中找可重用的cell
BNPSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//没找到就创建
if (cell == nil) {
cell = [[BNPSettingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
return cell;
}

//通过代码自定义cell需要重写以下方法,可以添加额外的控件.
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.viewLine = [[UIView alloc]init];

self.viewLine.backgroundColor = [UIColor blackColor];
self.viewLine.alpha = 0.2;

[self.contentView addSubview:self.viewLine];

}
return self;
}

//当父容器的frame发生改变时,会调用该方法,常常用来设置子控件的fram值
-(void)layoutSubviews{

//这里一定要先调用父类的方法,否则你会很痛苦T_T
[super layoutSubviews];
self.viewLine.frame = CGRectMake(0, self.height - 1, [UIScreen mainScreen].bounds.size.width, 1);
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: