UITableViewCell的循环利用 - 在storyboard里

#import "TableViewController.h"

@interface TableViewController ()

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //有20行
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row % 2 == 0) {
        // 1.重用标识
        //被static修饰的局部变量只会初始化一次,在整个程序运行的过程中只有一份内存
        static NSString *ID = @"cell";
        
        // 2.先根据cell的标识去缓存池中查询可以循环利用的cell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        
        // 3.如果cell为nil,意味着缓存池找不到对应的cell
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        
        //4.设置cell上显示的数据
        cell.textLabel.text = [NSString stringWithFormat:@"test - %zd",indexPath.row];
        
        return cell;

    }else{
        // 1.重用标识
        //被static修饰的局部变量只会初始化一次,在整个程序运行的过程中只有一份内存
        static NSString *ID = @"cell2";
        
        // 2.先根据cell的标识去缓存池中查询可以循环利用的cell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        
        // 3.如果cell为nil,意味着缓存池找不到对应的cell
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        
        //4.设置cell上显示的数据
        cell.textLabel.text = [NSString stringWithFormat:@"test - %zd",indexPath.row];
        
        return cell;
    }
    

}
@end
最后效果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值