IOS开发之——团购网站代码重构(39)

一 概述

本文从以下几点对代码进行重构:

  • XIB的属性面板,指定可重用标识符(Cell与XIB中的Identifier中的Cell一致)

  • 通过数据模型设置Cell内容,可以让视图控制器不需要了解Cell的内部实现细节

  • 在TgCell中提供一个类方法,可以快速创建Cell

<!--more-->

二 重构

2.1 XIB面板,重用标识符

TgCell.m面板标识符

+(instancetype)cellWithTableView:(UITableView *)tableView
{
    //1.可重用标识符
    static NSString *ID=@"Cell";
    //2.tableView查询可重用Cell
    TgCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    //3.如果没有可重用cell
    if (cell==nil) {
        NSLog(@"加载XIB");
        cell=[[[NSBundle mainBundle]loadNibNamed:@"TgCell" owner:nil options:nil]lastObject];
    }
    return cell;
}

TgCell.xib面板

 

2.2 通过数据模型设置Cell内容

TgCell.h

@property (nonatomic,strong) TG *tg;

TgCell.m

- (void)setTg:(TG *)tg 
{
    //setter方法中,第一句要赋值
    _tg=tg;
    self.titleLabel.text=tg.title;
    self.iconView.image=[UIImage imageNamed:tg.icon];
    self.priceLabel.text=tg.price;
    self.buyCountLabel.text=tg.buyCount;  
}

2.3 提供一个类方法,可以快速创建Cell

TgCell.h

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

TgCell.m

+(instancetype)cellWithTableView:(UITableView *)tableView
{
    //1.可重用标识符
    static NSString *ID=@"Cell";
    //2.tableView查询可重用Cell
    TgCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    //3.如果没有可重用cell
    if (cell==nil) {
        NSLog(@"加载XIB");
        cell=[[[NSBundle mainBundle]loadNibNamed:@"TgCell" owner:nil options:nil]lastObject];
    }
    return cell;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值