iOS UITableViewCell重用机制避免重复显示问题
来源:互联网 发布:面板数据主成分分析 编辑:程序博客网 时间:2024/05/11 19:04
常规配置如下 当超过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 = @"text";
- cell.detailTextLabel.text = @"text";
- cell.imageView.image = [UIImage imageNamed:@"4.png"];
-
- return cell;
- }
-
-
-
方案一 取消cell的重用机制,通过indexPath来创建cell 将可以解决重复显示问题 不过这样做相对于大数据来说内存就比较吃紧了
-
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
-
- static NSString *CellIdentifier = @"Cell";
-
- UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
-
- if (!cell) {
- cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
- }
-
- cell.textLabel.text = @"text";
- cell.detailTextLabel.text = @"text";
- cell.imageView.image = [UIImage imageNamed:@"4.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];
-
- if (!cell) {
- cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
- }
-
- cell.textLabel.text = @"text";
- cell.detailTextLabel.text = @"text";
- cell.imageView.image = [UIImage imageNamed:@"4.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
- {
- while ([cell.contentView.subviews lastObject] != nil) {
- [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
- }
- }
-
- cell.textLabel.text = @"text";
- cell.detailTextLabel.text = @"text";
- cell.imageView.image = [UIImage imageNamed:@"4.png"];
-
- return cell;
- }
0 0