//通常我們是這樣來是cell重用
//如果超過頁面顯示的內(nèi)容就會重復(fù)出現(xiàn),遇到重復(fù)顯示的Bug
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"Cell";
// 通過唯一標(biāo)識創(chuàng)建cell實(shí)例
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
// 判斷為空進(jìn)行初始化 --當(dāng)拉動頁面顯示超過主頁面內(nèi)容的時(shí)候就會重用之前的cell,而不會再次初始化
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = @"text";
cell.imageView.image = [UIImage imageNamed:@"imageName"];
return cell;
}
解決方案有以下幾種
//1)思路:不設(shè)置cell的重用機(jī)制,通過indexPath來創(chuàng)建cell,來解決重復(fù)顯示的問題,在數(shù)據(jù)量大的情況下不推薦使用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"Cell";
// 通過indexPath創(chuàng)建cell實(shí)例 每一個(gè)cell都是單獨(dú)的
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// 判斷為空進(jìn)行初始化 --(當(dāng)拉動頁面顯示超過主頁面內(nèi)容的時(shí)候就會重用之前的cell,而不會再次初始化)
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.textLabel.text = @"text";
cell.imageView.image = [UIImage imageNamed:@"imageName"];
return cell;
}
//2)思路:讓每個(gè)cell都有一個(gè)對應(yīng)的標(biāo)識 這樣做也會讓cell無法重用 所以也就不會是重復(fù)顯示了 同樣在數(shù)據(jù)量大的情況下不推薦使用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = [NSString stringWithFormat:@"cell%ld%ld",indexPath.section,indexPath.row];
// 通過indexPath創(chuàng)建cell實(shí)例 每一個(gè)cell都是單獨(dú)的
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// 判斷為空進(jìn)行初始化 --(當(dāng)拉動頁面顯示超過主頁面內(nèi)容的時(shí)候就會重用之前的cell组力,而不會再次初始化)
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.textLabel.text = @"text";
cell.imageView.image = [UIImage imageNamed:@"imageName"];
return cell;
}
3)思路:只要最后一個(gè)顯示的cell內(nèi)容不為空叙身,然后把它的子視圖全部刪除,等同于把這個(gè)cell單獨(dú)出來了 然后跟新數(shù)據(jù)就可以解決重復(fù)顯示
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"Cell";
// 通過唯一標(biāo)識創(chuàng)建cell實(shí)例
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}else//當(dāng)頁面拉動的時(shí)候 當(dāng)cell存在并且最后一個(gè)存在 把它進(jìn)行刪除就出來一個(gè)獨(dú)特的cell我們在進(jìn)行數(shù)據(jù)配置即可避免
{
while ([cell.contentView.subviews lastObject] != nil) {
[(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
}
}
cell.textLabel.text = @"text";
cell.imageView.image = [UIImage imageNamed:@"imageName"];
return cell;
}