在使用UITableView做开发时,常常会遇到 系统提供的样式无法满足项目需求的情况,这时就需要根据需求来自定义cell。
自定义cell有两种方式:
· 通过xib自定义cell(适用于cell中子控件个数固定、cell样式统一的结构,例如:商品的列表页面)
· 通过代码自定义cell(适用于cell中子控件个数不固定、cell样式不统一的结构,例如:微博列表)
通过xib创建自定义cell基本步骤(商品列表例子):
1.创建一个xib文件描述view ,设置数据源为控制器
TgCell.xib
2.新建一个新的类(继承自系统自带的某个view,继承自哪个类,取决于xib根对象的Class)
新建类的类名最好跟xib的文件名保持一致
将xib中的控件与自定义类进行连线
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *titleView;
@property (weak, nonatomic) IBOutlet UILabel *priceView;
@property (weak, nonatomic) IBOutlet UILabel *countView;
包含一个模型数据属性
@property (strong, nonatomic) Tg *tg;
重写模型数据的setter方法 和 构造方法
//构造方法
+(instancetype)tgCellWithTableView:(UITableView *)tableView
{
//cell的标识符
static NSString *ID = @"TGID";
//从缓冲池中拿到标识符是ID的cell对象
TgCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
//如果没有找到缓冲池中的对象,
//则新建一个 通过loadNibNamed 方法从xib返回cell对象
cell = [[[NSBundle mainBundle] loadNibNamed:@"TgCell" owner:nil options:nil] lastObject];
}
return cell;
}
//setter方法
-(void)setTg:(Tg *)tg
{
_tg = tg;
//图片
self.iconView.image = [UIImage imageNamed:self.tg.icon];
//标题
self.titleView.text = self.tg.title;
//价格
self.priceView.text = [NSString stringWithFormat:@"¥ %@",self.tg.price];
//人数
self.countView.text = [NSString stringWithFormat:@"%@人已购买",self.tg.buyCount];
}
3.控制器中
1)遵守TableView的数据源协议 <UITableViewDataSource>
@interface ViewController () <UITableViewDataSource>
@end
1)包含模型数据属性,并拿到TableView对象
@property (strong, nonatomic) NSArray *tgInfo;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
2)重写数据模型的setter方法,实现数据从文件到模型的转换
/**
tgInfo的get方法实现懒加载
*/
-(NSArray *)tgInfo
{
if (_tgInfo == nil) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"tgs.plist" ofType:nil];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *tgArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
Tg *tg = [Tg tgWithDict:dict];
[tgArray addObject:tg];
}
_tgInfo = tgArray;
}
return _tgInfo;
}
3)重写TableView的数据源方法
/**
每组有多少行数据
*/
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.tgInfo.count;
}
/**
设置每条数据
*/
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1.创建cell
TgCell *cell = [TgCell tgCellWithTableView:tableView];
//2.给cell传递模型数据
cell.tg = self.tgInfo[indexPath.row];
return cell;
}