UITableViewCell重用
- 基本的重用方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 0 重用标识
// 被static修饰的局部变量,只会出初始化一次,在整个程序运行尘中,只有一分内存
static NSString *ID = @"cell";
// 1. 先根据cell的标识去缓存池中查找可循环利用cell
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:@"test - %zd",indexPath.row];
return cell;
}
cell优化
- 在viewController项目中创建一个继承UITableViewController的类,然后在storyboard托一个UITableViewController之后修改cell标识 就可以了.
代码案例
#import "ZJTestViewController.h"
@interface ZJTestViewController ()
@end
@implementation ZJTestViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 0 重用标识
// 被static修饰的局部变量,只会出初始化一次,在整个程序运行尘中,只有一分内存
static NSString *ID = @"cell";
// 1. 先根据cell的标识去缓存池中查找可循环利用cell
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 如果在storyboard中设置了 标识,即便是第一次为空 也不需要再次创建了, 因为他会默认首先在storyboard中找cell的标识. 因为我在storyboard中设置了cell标识,所以这里不需要在进行判断.
// // 2. 如果cell为nil(缓存池找不到对应的cell)
// if (cell == nil) {
// cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
// }
//
// 3.覆盖数据
cell.textLabel.text = [NSString stringWithFormat:@"test - %zd",indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//...
}
// 当然cell重用的写法还有很多,如果想减少这个方法中的代码,我们也可以另写一个方法,然后传递参数就可以实现,具体用法,以后会在项目中进行操作
尽情期待后期更新…