2013-12-23 5 views
0

В следующем коде текст повторяется для следующих строк: UILabel. Я знаю, что это проблема с возможностью повторного использования таблицы, но не могу понять, как ее решить. Все выглядит нормально даже при подсчете.Повторное использование UITableViewCell в нескольких разделах

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath 
{ 
UITableViewCell *cell; 

//Doc Name 
if(indexPath.section == 0) 
{ 
    cell=[tableView dequeueReusableCellWithIdentifier:@"cell"]; 

    if(cell==nil) 
    { 
     cell= [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]autorelease]; 

    } 

    cell.textLabel.text= docName; 
    cell.textLabel.font=[UIFont fontWithName:@"Times New Roman" size:17.f]; 

    UILabel *name = [[UILabel alloc]init]; 
    name.backgroundColor = [UIColor clearColor]; 
    name.textAlignment = NSTextAlignmentCenter; 
    name.frame = CGRectMake(600,2.0f,250,50); 
    name.text = @"11:12:01"; 
    [cell addSubview:name]; 

} 

//Joint Work 
if(indexPath.section == 1) 
{ 
    cell=[tableView dequeueReusableCellWithIdentifier:@"cell"]; 

    if(cell==nil) 
    { 
     cell= [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]autorelease]; 

    } 

    cell.textLabel.text= [jointWrkNames objectAtIndex:indexPath.row]; 
    cell.textLabel.font=[UIFont fontWithName:@"Times New Roman" size:17.f]; 
} 

//Detailing 
if(indexPath.section == 2) 
{ 
    cell=[tableView dequeueReusableCellWithIdentifier:@"cell"]; 

    if(cell==nil) 
    { 
     cell= [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]autorelease]; 

    } 

    cell.textLabel.text= @"Detailing"; 
    cell.textLabel.font=[UIFont fontWithName:@"Times New Roman" size:17.f]; 
} 
} 
+0

Используйте разные идентификаторы ячеек для иной, если заявления, в противном случае та же ячейка из очереди, и использовать повторно. Это довольно просто. – n00bProgrammer

+0

Я не вижу, где вы вернете ячейку. Я был бы удивлен, если бы это сработало. – Jeremy

+0

Я возвращаю камеру. он не пришел, когда я скопировал его. – LeXeR

ответ

3
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath 
{ 
UITableViewCell *cell; 

//Doc Name 
if(indexPath.section == 0) 
{ 
    cell=[tableView dequeueReusableCellWithIdentifier:@"section_0_cell"]; 

    if(cell==nil) 
    { 
     cell= [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"section_0_cell"]autorelease]; 

    } 

    cell.textLabel.text= docName; 
    cell.textLabel.font=[UIFont fontWithName:@"Times New Roman" size:17.f]; 

    UILabel *name = [[UILabel alloc]init]; 
    name.backgroundColor = [UIColor clearColor]; 
    name.textAlignment = NSTextAlignmentCenter; 
    name.frame = CGRectMake(600,2.0f,250,50); 
    name.text = @"11:12:01"; 
    [cell addSubview:name]; 

} 

//Joint Work 
if(indexPath.section == 1) 
{ 
    cell=[tableView dequeueReusableCellWithIdentifier:@"section_1_cell"]; 

    if(cell==nil) 
    { 
     cell= [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"section_1_cell"]autorelease]; 

    } 

    cell.textLabel.text= [jointWrkNames objectAtIndex:indexPath.row]; 
    cell.textLabel.font=[UIFont fontWithName:@"Times New Roman" size:17.f]; 
} 

//Detailing 
if(indexPath.section == 2) 
{ 
    cell=[tableView dequeueReusableCellWithIdentifier:@"section_2_cell"]; 

    if(cell==nil) 
    { 
     cell= [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"section_2_cell"]autorelease]; 

    } 

    cell.textLabel.text= @"Detailing"; 
    cell.textLabel.font=[UIFont fontWithName:@"Times New Roman" size:17.f]; 
} 
return cell; 
} 

Для успешного повторного использования, если соответствующая ячейка, то cellIdentifier должна быть уникальной для различных типов клеток. Следовательно, для каждого раздела используется другой идентификатор.

+0

thanx приятель, ваш метод работал как шарм. Просто изменение «CellIdentifier» сделало трюк. Тонкс снова. – LeXeR

+0

Рад, что я мог помочь. – n00bProgrammer

+0

Где вы будете использовать ячейку в виде таблицы? – NANNAV

0

Ну вы просто должны удалить экземпляры из UILabel's в каждой ячейке UITableView перед каждой перезагрузке UITableView. Это поможет вам

После создания ячейки как

static NSString *cellIdentifier = @"Identifier";   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];   
    if(cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil]; 
    } 

Добавить это

for(id obj in cell.contentView.subviews) 
    { 
     if([obj isKindOfClass:[UILabel class]]) 
     { 
      [obj removeFromSuperview]; 
     } 
    } 

Надежда ваш вопрос очищается сейчас

+0

удаление и добавление UIlabel кажется сложным. Я думаю, что изменение идентификатора выглядит просто. – LeXeR

+0

Ну, теперь вы подумаете, что это просто, но u havnt 'столкнулся с проблемами ...: D ... И еще более длинный ... скажем, у вас более 10 разделов, и вы думаете, что добавите еще 10 строки кода для каждого раздела? Подумайте об этом ... – IronManGill

0

Сделать выделение ярлыка, если ячейка создается т.е. когда клетка равна нулем

if(cell==nil) 
    { 
      cell= [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]autorelease]; 
      UILabel *name = [[UILabel alloc]init]; 
    } 
+0

Недостаточно, чтобы преодолеть эту проблему. –

0

Простой способ повторного использования ячейки в таблице View

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

    if(cell==nil) 
    { 
     cell= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"section_0_cell"]; 
     cell.textLabel.font=[UIFont fontWithName:@"Times New Roman" size:17.f]; 
     UILabel *name = [[UILabel alloc]init]; 
     name.backgroundColor = [UIColor clearColor]; 
     name.textAlignment = NSTextAlignmentCenter; 
     name.frame = CGRectMake(600,2.0f,250,50); 

     [cell addSubview:name]; 
     name.tag=100; 
    } 

    UILabel *name = (UILabel*)[cell viewWithTag:100]; 
    name.hidden=YES; 
    //Doc Name 
    if(indexPath.section == 0) 
    { 
     name.hidden=NO; 
     cell.textLabel.text= docName; 
     name.text = @"11:12:01"; 
    } 

    //Joint Work 
    if(indexPath.section == 1) 
    { 
     cell.textLabel.text= [jointWrkNames objectAtIndex:indexPath.row]; 
    } 

    //Detailing 
    if(indexPath.section == 2) 
    { 
     cell.textLabel.text= @"Detailing"; 
    } 
    return cell; 
} 
Смежные вопросы