Matt
Matt

Reputation: 2930

UITableView cell labels moving around when scrolling

I created a uitableview and when i launch it, it looks as it is supposed to, but when I scroll, it puts text in all the other sections that I don't specify, can someone please help. The first image attached is how it should look. The second it what it does when I scroll.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 ){
        return 1;}
    else if (section == 1){
        return [cellLabels count];
    }else if (section == 2){
        return 1;
    }else{
        return 0;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    tableView.showsVerticalScrollIndicator = NO;
    // cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;


    if( indexPath.section == 0 )
    {
    }
    else if (indexPath.section == 1)
    {
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor = [UIColor blackColor];
        // headerLabel.font = [UIFont SystemFontOfSize:16];
        [cell.textLabel setFont:[UIFont fontWithName:@"Arial" size:14]];
        cell.textLabel.text = [cellLabels objectAtIndex:indexPath.row];


    }
return cell;

}

This is what is looks like when it is launched, and what it is supposed to look like

enter image description here

Upvotes: 0

Views: 761

Answers (1)

Pavan
Pavan

Reputation: 443

your problem is pretty simple ,

since table view reuses allocated cells, when it comes to first time to first section your displaying nothing , in second section displaying your custom texts

when it scrolls down and come back it text will appear in first section because when it reaches

if( indexPath.section == 0 )
{
}

it wont do anything so

make it

if( indexPath.section == 0 )
{
   cell.textLabel.text = @"";
}
else if( indexPath.section == 2 )
{
   cell.textLabel.text = @"";
}

or

if( indexPath.section == 0 )
{
   cell.textLabel.text = nil;
}

else if( indexPath.section == 2 )
{
   cell.textLabel.text = nil;
}

other FOR SECTION 1 is correct

Upvotes: 1

Related Questions