一般习惯上我们都会按照下面的方法来写 、当超过tableView显示的范围的时候 、后面显示的内容将会和前面重复
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = @"titel";
cell.detailTextLabel.text = @"detail";
cell.imageView.image = [UIImage imageNamed:@"xxx.png"];
return cell;
}
解决方案如下:
方案一
取消cell的重用机制、通过indexPath来创建cell、 将可以解决重复显示问题 、不过这样做缺点就是相对于大数据来说内存压力就比较大
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
// 通过indexPath创建cell实例 每一个cell都是单独的
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = @"titel";
cell.detailTextLabel.text = @"detail";
cell.imageView.image = [UIImage imageNamed:@"xxx.png"];
return cell;
}
方案二
让每个cell都拥有一个对应的标识 、这样做也会让cell无法重用 、缺点跟第一个一样数据太多会造成内存压力就比较大
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// 判断为空进行初始化 --(当拉动页面显示超过主页面内容的时候就会重用之前的cell,而不会再次初始化)
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = @"titel";
cell.detailTextLabel.text = @"detail";
cell.imageView.image = [UIImage imageNamed:@"xxx.png"];
return cell;
}
方案三
当最后一个显示的cell内容不为空、然后把它的子视图全部删除,相当于把这个cell单独分离出来、 然后刷新数据就可以解决重复显示
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
} else {
//当页面拉动的时候 当cell存在并且最后一个存在 把它进行删除就出来一个独特的cell我们在进行数据配置即可避免
while ([cell.contentView.subviews lastObject] != nil) {
[(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
}
}
cell.textLabel.text = @"titel";
cell.detailTextLabel.text = @"detail";
cell.imageView.image = [UIImage imageNamed:@"xxx.png"];
return cell;
}
大概目前就用了这几种,希望对大家能有点滴帮助,也希望还有最优方案的朋友,欢迎随时@,一起学习,谢谢!