Data repeat in UITableView when scrolling

前端 未结 4 1895
青春惊慌失措
青春惊慌失措 2020-12-10 22:46

I use bellow codes to show data on TableView but when scrolling, data repeat and other data lost.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tab         


        
4条回答
  •  情话喂你
    2020-12-10 23:30

    You are setting the text of the label only when creating a new cell. However, during cell reuse, new cell is not created. Hence your code for setting/changing text is not working. You can use this modified code.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
        static NSString *CellIdentifier = @"CellIdentifier";
    
        UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        UILabel *FileNameLabel=nil;
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
            FileNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
            FileNameLabel.tag = 1001;
            FileNameLabel.backgroundColor = [UIColor clearColor];
            FileNameLabel.font = [UIFont fontWithName:@"Helvetica" size:16];
            FileNameLabel.font = [UIFont boldSystemFontOfSize:16];
            FileNameLabel.textColor = [UIColor blackColor];
            [cell.contentView addSubview: FileNameLabel];
            [FileNameLabel release];
        }
        if(!FileNameLabel)
            FileNameLabel = [cell.contentView viewWithTag:1001];
        FileNameLabel.text =[FileCompletedArray objectAtIndex:indexPath.row];
    
        return cell;
    }
    

    Alternatively you can use the default textLabel instead of creating and adding new label

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        static NSString *CellIdentifier = @"CellIdentifier";
    
        UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        UILabel *FileNameLabel=nil;
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:16];
            cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
            cell.textLabel.textColor = [UIColor blackColor];
        }
        cell.textLabel.text =[FileCompletedArray objectAtIndex:indexPath.row];
    
        return cell;
    }
    

提交回复
热议问题