Day.03.03 UITableView 单元格的复用


#import "ViewController.h"

//宏定义
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    
    NSInteger _newCount;//记录创建次数
    
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _newCount = 0 ;
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    tableView.dataSource = self;
    
    tableView.delegate = self;
    
    tableView.rowHeight = 70;
    
    [self.view addSubview:tableView];
    
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    /**
     *  单元格复用:
     屏幕上至多能显示N个单元格,那么我们一共需要创建N+1单元格,即可完成表视图的显示任务
     
     优势:节省内存
     */
    
    
    //1.设置一个单元格重用的标记 identifier 字符串
    static NSString *identifier = @"qq_cell";
    
    //2.判断屏幕显示的单元格外 是否有带有标记的cell
    
    //如果存在reuse cell 则直接显示
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    //如果不存在reuse cell 则创建新cell
    if (cell == nil) {
        
        _newCount ++;
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        
        NSLog(@"创建第%ld个单元格",_newCount);
        
        /*_______________________________________________________________*/
        
        //✅单元格的共性-->定制单元格的样式
        
        UILabel *label = [[UILabel alloc]initWithFrame:cell.bounds];
        
        label.font = [UIFont boldSystemFontOfSize:30];
        
        label.textColor = [UIColor greenColor];
        
        label.tag = 101;
        
        [cell addSubview:label];
        
        //❌内容一定在大括号外写
        //        label.text = [NSString stringWithFormat:@"%ld %ld",indexPath.section,indexPath.row];
        
    }
    
    /*_______________________________________________________________*/
    
    //✅单元格的个性-->填充单元格的内容
    
    UILabel *cellLabel = [cell viewWithTag:101];
    
    cellLabel.text = [NSString stringWithFormat:@"%ld %ld",indexPath.section,indexPath.row];
    
    
        cell.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    
    
    //3.返回
    return cell;
        
}
@end

屏幕快照 2016-03-03 上午9.38.13.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容