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

iOS自定义UITableView的cell

2014-12-10 00:00 363 查看
摘要: 使用xib创建一个自定义的cell.
一,注意设置改自定义cell的标识,这样使用缓冲池来访问cell时才可以访问到.
二,声明一个继承自UITableViewCell的类,用它来管理xib(自定义cell),方便数据管理.
三,注意xib中设置class为二中的继承UITableViewCell的类,而不是UITableView类.

//-------该类用来管理MLTgCell.xib
#import <UIKit/UIKit.h>
@class MLTg;
@interface MLTgCell : UITableViewCell

//将团购模型传给cell
@property(nonatomic, strong) MLTg *tg;

-(void) setTg:(MLTg *)tg;

+(instancetype)cellWithTableView:(UITableView *)tableView;
-(instancetype)initWithTableView:(UITableView *)tableView;

@end

#import "MLTgCell.h"
#import "MLTg.h"
@interface MLTgCell()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *titleView;
@property (weak, nonatomic) IBOutlet UILabel *priceView;
@property (weak, nonatomic) IBOutlet UILabel *buyCountView;

@end

@implementation MLTgCell

-(instancetype)initWithTableView:(UITableView *)tableView{
static NSString *ID = @"tg";
MLTgCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
//使用xib来创建自定义cell
//---在xib中需要给cell设置标识tg,否则缓存池中取不到带有ID标识的cell.
cell = [[[NSBundle mainBundle] loadNibNamed:@"MLTgCell" owner:nil options:nil] firstObject];
}
return cell;
}

+(instancetype)cellWithTableView:(UITableView *)tableView{
return [[self alloc] initWithTableView:tableView];
}
-(void) setTg:(MLTg *)tg{
_tg = tg;
//设置图片
self.iconView.image = [UIImage imageNamed:tg.icon];
//设置title
self.titleView.text = tg.title;
//设置价格
self.priceView.text = [NSString stringWithFormat:@"¥%@", tg.price];
//设置购买的数量
self.buyCountView.text = [NSString stringWithFormat:@"%@人已购买",tg.buyCount];
}

@end

//----------数据模型类,用来传递数据-------
#import <Foundation/Foundation.h>

@interface MLTg : NSObject

@property(nonatomic, copy) NSString *buyCount;
@property(nonatomic, copy) NSString *icon;
@property(nonatomic, copy) NSString *price;
@property(nonatomic, copy) NSString *title;

+(instancetype)tgWithDict:(NSDictionary *)dict;
-(instancetype)initWithDict:(NSDictionary *)dict;

@end

#import "MLTg.h"

@implementation MLTg

+(instancetype)tgWithDict:(NSDictionary *)dict{
return [[self alloc]initWithDict:dict];
}
-(instancetype)initWithDict:(NSDictionary *)dict{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}

@end

//-------控制器中用来返回自定义cell的方法
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//创建cell(屏蔽了cell是通过什么方式创建的(代码或xib方式))
MLTgCell *cell = [MLTgCell cellWithTableView:tableView];

//给cell传递模型数据.
cell.tg = self.tgs[indexPath.row];

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