您的位置:首页 > 其它

自定义等高的cell(xib)

2016-02-04 23:11 351 查看
/*
xib自定义cell
1.创建一个继承自UITabelViewCell的子类,比如tgCell
2.创建一个xib文件(文件名建议跟cell的类名一样),比如tgCell.xib
拖一个UITabelViewCell控件;
修改cell的class属性为tgCell;
设置重用标识;
往cell中添加需要的子控件
3.在控制器中
创建cell;
给cell传递模型数据
4.在tgCell中
提供一个创建cell的类方法;
提供一个模型属性,重写该属性的set方法,设置模型数据到子控件上;
*/




//
//  tgCell.h

#import <UIKit/UIKit.h>

@class tgModel;

@interface tgCell : UITableViewCell
/**
*  团购模型数据
*/
@property(nonatomic,strong)tgModel *model;

/**
*  创建一个cell
*/
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end
//
//  tgCell.m

#import "tgCell.h"
#import "tgModel.h"

@interface tgCell()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *buycountLabel;

@end

@implementation tgCell

- (void)setModel:(tgModel *)model
{
_model = model;

//设置数据
self.iconView.image = [UIImage imageNamed:model.icon];
self.titleLabel.text = model.title;
self.priceLabel.text = [NSString stringWithFormat:@"¥%@",model.price];
self.buycountLabel.text = [NSString stringWithFormat:@"%@人已购买",model.buyCount];
}

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
static NSString *ID = @"cell";
tgCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([tgCell class]) owner:nil options:nil] lastObject];
}

return cell;
}

@end



//
//  TableViewController.m

#import "TableViewController.h"
#import "tgModel.h"
#import "tgCell.h"

@interface TableViewController ()
/** 所有团购数据 */
@property(nonatomic,strong) NSArray *tgs;
@end

@implementation TableViewController

- (NSArray *)tgs
{
if (_tgs == nil) {
// 加载plist文件中的字典数组
NSString *path = [[NSBundle mainBundle] pathForResource:@"tgs.plist" ofType:nil];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];

// 字典数组 -> 模型数组
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
tgModel *model = [tgModel tgWithDict:dict];
[arrayM addObject:model];
}

_tgs = arrayM;
}
return _tgs;
}

- (void)viewDidLoad {
[super viewDidLoad];

//    //注册xib
//    UINib *nib = [UINib nibWithNibName:NSStringFromClass([tgCell class]) bundle:nil];
//    [self.tableView registerNib:nib forCellReuseIdentifier:@"cell"];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.tgs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 创建cell的过程封装到cell类中
tgCell *cell = [tgCell cellWithTableView:tableView];

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

return cell;
}

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