// ViewController.m
// 單元格復(fù)用
//
// Created by Beiwo on 16/2/29.
// Copyright ? 2016年 你國哥. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
NSInteger _newCount;//記錄創(chuàng)建次數(shù)
}
@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{
/*———————————————————————————————核心———————————————————————————————————————————*/
/*
單元格復(fù)用:
屏幕上之多能顯示N個單元格,那么我們一共需要創(chuàng)建N+1單元格,即可完成表視圖的顯示任務(wù)
優(yōu)勢:節(jié)省內(nèi)存
*/
//1.設(shè)置一個單元格重用的標(biāo)記 identifier 字符串
static NSString *identifier = @"qq_cell";
//2.判斷屏幕顯示的單元格外 是否有帶有標(biāo)記的cell
//如果存在顯示reuse cell 則直接顯示
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//如果不存在reuse cell 則創(chuàng)建新cell
if (cell == nil) {
_newCount++;
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
NSLog(@"創(chuàng)建第%ld個單元格",_newCount);
/*———————————————————————————————核心—————————————————————————————————————*/
//單元格的共性
UILabel *label = [[UILabel alloc]initWithFrame:cell.bounds];
label.font = [UIFont boldSystemFontOfSize:30];
label.textColor = [UIColor redColor];
label.tag = 101;
[cell addSubview:label];
}
//內(nèi)容一定在大括號外面
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