纯代码实现自定义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
相关文章推荐
- 在android studio中添加.jar文件后,rebuild不报错,执行报错的解决
- Qt Gui使用(一)
- java基础学习总结——GUI编程(二)
- jJMeter UDP Request:不等待服务器响应
- java基础学习总结——GUI编程(一)
- 生成器模式 (Builder)
- STL学习笔记— —特殊容器queue
- Java队列Queue、双端队列Deque
- keras中models的Squential类的源码简介
- iOS--Quartz2D使用(自定义UIImageView控件、绘制基本图形)
- UiViewController 里frame和bounds取值有误
- UESTC 491 Tricks in Bits
- UESTC 491 Tricks in Bits
- UESTC 485 Game(康托,BFS)
- UESTC 485 Game(康托,BFS)
- Unreal Engine 4 —— 冷却UI的制作
- Unreal Engine 4 —— 冷却UI的制作
- UITableView - beginUpdates和endUpdates
- UIView常用的一些方法小记之setNeedsDisplay和setNeedsLayout
- datagrid 内嵌 combotree 显示 valueField 而不是 valueText 的解决办法