Day.02.29 单元格复用
2016-02-29 本文已影响43人
挂树上的骷髅怪
// ViewController.m
// 单元格复用
//
// Created by Beiwo on 16/2/29.
// Copyright © 2016年 你国哥. All rights reserved.
//
#import "ViewController.h"
@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 redColor];
label.tag = 101;
[cell addSubview:label];
}
//内容一定在大括号外面
UILabel *cellLabel = [cell viewWithTag:101];
cellLabel.text = [NSString stringWithFormat:@"%ld %ld",indexPath.section,indexPath.row];
//返回
return cell;
}
@end
屏幕快照 2016-02-29 下午3.49.16.png