問題:
tableView是項目中常用的控件,若如下配置,超過頁面顯示的內(nèi)容會重復(fù)出現(xiàn):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 通過唯一標(biāo)識創(chuàng)建cell實例
static NSString *ID = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 判斷為空進(jìn)行初始化 --(當(dāng)拉動頁面顯示超過主頁面內(nèi)容的時候就會重用之前的cell,而不會再次初始化)
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
cell.textLabel.text = [NSString stringWithFormat:@"%zd",indexPath.row];
return cell;
}
解決:
方法1:取消重用機制,通過indexPath來創(chuàng)建cell
利弊:解決重復(fù)顯示問題,但如果數(shù)據(jù)比較多,內(nèi)存就比較吃緊
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 通過唯一標(biāo)識創(chuàng)建cell實例
static NSString *ID = @"Cell";
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// 判斷為空進(jìn)行初始化 --(當(dāng)拉動頁面顯示超過主頁面內(nèi)容的時候就會重用之前的cell,而不會再次初始化)
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
cell.textLabel.text = [NSString stringWithFormat:@"%zd",indexPath.row];
return cell;
}
方法2:取消重用機制,讓每個cell有一個獨立的標(biāo)識符,因為重用機制是根據(jù)相同的標(biāo)識符來重用cell的
利弊:解決重復(fù)顯示問題,但如果數(shù)據(jù)比較多,內(nèi)存同樣也會比較吃緊
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 通過唯一標(biāo)識創(chuàng)建cell實例
NSString *ID = [NSString stringWithFormat:@"CellIdentifier%zd%zd", indexPath.section, indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 判斷為空進(jìn)行初始化 --(當(dāng)拉動頁面顯示超過主頁面內(nèi)容的時候就會重用之前的cell,而不會再次初始化)
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
cell.textLabel.text = [NSString stringWithFormat:@"%zd",indexPath.row];
return cell;
}
方法3:刪除最后一個顯示的cell的所有子視圖,得到一個沒有空的cell,供其他cell重用。
利弊:解決重復(fù)顯示問題,重用了cell相對內(nèi)存管理來說是最好的方案
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 通過唯一標(biāo)識創(chuàng)建cell實例
static NSString *ID = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 判斷為空進(jìn)行初始化 --(當(dāng)拉動頁面顯示超過主頁面內(nèi)容的時候就會重用之前的cell,而不會再次初始化)
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}else {
//當(dāng)頁面拉動的時候 當(dāng)cell存在并且最后一個存在 把它進(jìn)行刪除
while ([cell.contentView.subviews lastObject] != nil) {
[(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
}
}
cell.textLabel.text = [NSString stringWithFormat:@"%zd",indexPath.row];
return cell;
}