//-------該類用來管理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; }