方式一
//被static修飾的局部變量:只會初始化一次,在整個程序運行過程中,只有一份內存
static NSString *ID = @"cell";
/**
* 什么時候調用:每當有一個cell進入視野范圍內就會調用
*/
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1. 設置重用標示
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//2.如果cell為nil(緩存池找不到對應的cell)
if(cell==nil){
cell = [[UITableViewCell alloc]initWithStyle:UITableVIewCellStyleDefault reuseIdentifier:ID];
}
//3.顯示數據
cell.textLabel.text = [NSString stringWithFormat:@"testDate - %zd",indexPath.row];
return cell;
}
方式二
- 定義全局變量
//定義重用標示符
NSString *ID = @"cell";
- 注冊某個標識對應cell類型
//在這個方法中注冊cell
-(void)viewDidLoad
{
[super viewDidLoad];
//注冊某個標識對應的cell類型
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
}
- 數據源方法中返回cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1.去緩存池中查找cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//2.顯示數據
cell.textLabel.text = [NSString stringWithFormat:@"testdata - %zd", indexPath.row];
return cell;
}
方式三
- 在storyboard中設置UITableView的Dynamic Prototypes Cell
Snip20150602_152.png
- 設置cell的重用標識
Snip20150602_153.png
- 在代碼中利用重用標識獲取cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1. 重用標識,被static修飾的局部變量:只會初始化一次,在整個程序運行過程中,只有一份內存
static NSString *ID = @"cell";
// 2. 先根據cell的標識去緩存池中查找可循環利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 3. 覆蓋數據
cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd", indexPath.row];
return cell;
}