2013-11-21 3 views
0

Когда я использую dequeReusableCell, и когда я прокручиваю вниз или вверх, содержимое последних ячеек (которое выходит из видимого экрана) накладывается, но работает, когда я каждый раз создаю новую ячейку. И я хочу использовать функциональные возможности dequereusble.Использование отсекаемой ячейки, перекрывающей содержимое ячеек uitableview после прокрутки

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

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

static NSString *[email protected]"Cell"; 

    //Code causing problem 
    /*UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    if(!cell) 
    { 
     cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    }*/ 

    //Code working fine 
    UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 

    UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 180, 20)]; 
    [titleLabel setFont:[UIFont boldSystemFontOfSize:15]]; 

    UIImageView *headerImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)]; 
    headerImageView.image=[UIImage imageNamed:@"offer_details.jpg"]; 

    UILabel *detailLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 30, 300, 20)]; 
    [detailLabel setFont:[UIFont systemFontOfSize:14]]; 

    UIButton *callButton=[[UIButton alloc]initWithFrame:CGRectMake(10, 30, 20, 20)]; 
    [callButton setBackgroundColor:[UIColor orangeColor]]; 

    MKMapView *mapView=[[MKMapView alloc] initWithFrame:CGRectMake(10, 30, 320, 200)]; 

    switch (indexPath.row) { 
     case 0: 
      [cell.contentView addSubview:headerImageView]; 
      [cell setBackgroundColor:[UIColor blackColor]]; 
      [email protected]"Get great offer Upto 20% Off"; 
      titleLabel.frame=CGRectMake(10, 220, 230, 20); 
      titleLabel.textColor=[UIColor colorWithRed:251.0/255.0f green:78.0f/255.0f blue:8.0f/255.0f alpha:1]; 
      detailLabel.frame=CGRectMake(10, 240, 300, 20); 
      detailLabel.textColor=[UIColor whiteColor]; 
      [email protected]"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt."; 
      [cell.contentView addSubview:detailLabel]; 
      break; 
     case 1: 
      [email protected]"Details"; 
      [email protected]"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "; 
      [cell.contentView addSubview:detailLabel]; 
      break; 
     case 2: 
      [email protected]"Collection Methods"; 
      [email protected]"Call and Reserve"; 
      detailLabel.frame=CGRectMake(50, 30, 300, 20); 
      [cell.contentView addSubview:detailLabel]; 
      [cell.contentView addSubview:callButton]; 
      break; 
     case 3: 
      [email protected]"Location"; 
      [cell.contentView addSubview:mapView]; 
      break; 
     case 4: 
      [email protected]"About us"; 
      [email protected]"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."; 
      [cell.contentView addSubview:detailLabel]; 
      break; 
     case 5: 
      [email protected]"Legal"; 
      [email protected]"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."; 
      [cell.contentView addSubview:detailLabel]; 

      break; 
     default: 
      break; 
    } 

    detailLabel.numberOfLines=0; 
    [detailLabel sizeToFit]; 
    [cell.contentView addSubview:titleLabel]; 


    return cell; 
} 

EDIT:

Будет ли я быть в состоянии использовать dequereusable ячейку, потому что содержимое моих строк не являются общими? Одна строка содержит изображение, одна содержит mapview, одна содержит только метки. Thanx заранее.

EDIT2:

@HRM теперь его показ подробно Lable пустым, за исключением первой ячейки

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

{ статический NSString * cellIdentifier = @ "Cell";

UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

//UITableViewCell *cell; 

if(!cell) 
{ 
    cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 

    UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 180, 20)]; 
    [titleLabel setFont:[UIFont boldSystemFontOfSize:13]]; 
    titleLabel.tag=1001; 

    [cell.contentView addSubview:titleLabel]; 
    switch (indexPath.row) { 
     case 0: 
     { 
      UIImageView *headerImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)]; 
      headerImageView.image=[UIImage imageNamed:@"offer_details.jpg"]; 
      headerImageView.tag=1002; 

      UILabel *detailLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 30, 300, 20)]; 
      [detailLabel setFont:[UIFont systemFontOfSize:12]]; 
      detailLabel.tag=1003; 
      detailLabel.numberOfLines=0; 
      [detailLabel sizeToFit]; 
      [cell.contentView addSubview:headerImageView]; 
      [cell.contentView addSubview:detailLabel]; 
     } 
      break; 

     case 1: 
     { 
      UILabel *detailLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 30, 300, 20)]; 
      [detailLabel setFont:[UIFont systemFontOfSize:12]]; 
      detailLabel.numberOfLines=0; 
      [detailLabel sizeToFit]; 
      [cell.contentView addSubview:detailLabel]; 
      detailLabel.tag=1004; 
     } 
      break; 
     case 2: 
     { 
      UILabel *detailLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 30, 300, 20)]; 
      [detailLabel setFont:[UIFont systemFontOfSize:12]]; 
      UIButton *callButton=[[UIButton alloc]initWithFrame:CGRectMake(10, 30, 15, 15)]; 
      [callButton setBackgroundColor:[UIColor orangeColor]]; 
      detailLabel.numberOfLines=0; 
      [detailLabel sizeToFit]; 
      [cell.contentView addSubview:detailLabel]; 
      detailLabel.tag=1005; 
      [cell.contentView addSubview:callButton]; 
     } 
      break; 
     case 3: 
     { 
      MKMapView *mapView=[[MKMapView alloc] initWithFrame:CGRectMake(0, 30, 320, 140)]; 
      [cell.contentView addSubview:mapView]; 
     } 
      break; 
     case 4: 
     { 
      UILabel *detailLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 30, 300, 20)]; 
      [detailLabel setFont:[UIFont systemFontOfSize:12]]; 
      detailLabel.tag=1006; 
      detailLabel.numberOfLines=0; 
      [detailLabel sizeToFit]; 
      [cell.contentView addSubview:detailLabel]; 
     } 
      break; 
     case 5: 
     { 
      UILabel *detailLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 30, 300, 20)]; 
      [detailLabel setFont:[UIFont systemFontOfSize:12]]; 
      detailLabel.tag=1007; 
      detailLabel.numberOfLines=0; 
      [detailLabel sizeToFit]; 
      [cell.contentView addSubview:detailLabel]; 
     } 
      break; 
     default: 
      break; 
    } 
} 


switch (indexPath.row) { 
    case 0: 
    { 
     [cell setBackgroundColor:[UIColor blackColor]]; 
     UILabel *titleLabel = (UILabel*)[cell.contentView viewWithTag:1001]; 
     UILabel *detailLabel=(UILabel*)[cell.contentView viewWithTag:1003]; 
     [email protected]"Get great offer Upto 20% Off"; 
     titleLabel.frame=CGRectMake(10, 210, 230, 20); 
     titleLabel.textColor=[UIColor colorWithRed:251.0/255.0f green:78.0f/255.0f blue:8.0f/255.0f alpha:1]; 
     detailLabel.frame=CGRectMake(10, 230, 300, 20); 
     detailLabel.textColor=[UIColor whiteColor]; 
     [email protected]"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt."; 
    } 
     break; 
    case 1: 
    { 
     UILabel *titleLabel = (UILabel*)[cell.contentView viewWithTag:1001]; 
     UILabel *detailLabel=(UILabel*)[cell.contentView viewWithTag:1004]; 
     [email protected]"Details"; 
     [email protected]"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "; 
    } 
     break; 
    case 2: 
    { 
     UILabel *titleLabel = (UILabel*)[cell.contentView viewWithTag:1001]; 
     UILabel *detailLabel=(UILabel*)[cell.contentView viewWithTag:1005]; 
     [email protected]"Collection Methods"; 
     [email protected]"Call and Reserve"; 
     detailLabel.frame=CGRectMake(30, 30, 300, 20); 

    } 
     break; 
    case 3: 
    { 
     UILabel *titleLabel = (UILabel*)[cell.contentView viewWithTag:1001]; 
     [email protected]"Location"; 
    } 
     break; 
    case 4: 
    { 
     UILabel *titleLabel = (UILabel*)[cell.contentView viewWithTag:1001]; 
     UILabel *detailLabel=(UILabel*)[cell.contentView viewWithTag:1006]; 
     [email protected]"About us"; 
     [email protected]"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \n\n Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."; 
    } 
     break; 
    case 5: 
    { 
     UILabel *titleLabel = (UILabel*)[cell.contentView viewWithTag:1001]; 
     UILabel *detailLabel=(UILabel*)[cell.contentView viewWithTag:1007]; 
     [email protected]"Legal"; 
     [email protected]"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \n\n Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."; 

    } 
     break; 
    default: 
     break; 
} 





return cell; 

}

+2

Почему вы прокомментировали условие 'if (! Cell)'? –

+0

Не связано ли это с повторно используемой ячейкой? – ViruMax

+0

u должен убедиться, что 'dequeue' происходит правильно, поэтому вам нужна эта проверка. –

ответ

1

При использовании dequeueReusableCellWithIdentifier, то Tableview будет повторно использовать существующую ячейку, и в вашем коде, вы пытаетесь создать новые элементы управления снова и снова, и, следовательно, он будет перекрываться. Лучший способ сделать это будет таким. Пожалуйста, пройдите это. Надеюсь, поможет.

ОБНОВЛЕНИЕ на основе вашего комментария.

static NSString *cellIdentifier= @"Cell"; 
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

//If tableView dont have cell available for reuse, then 
//create a new cell and attach the controls to it 
if(cell == nil) 
{ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 

    if(indexPath.row == 0){ 

     UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 180, 20)]; 
    [titleLabel setFont:[UIFont boldSystemFontOfSize:15]]; 
     titleLabel.tag = 1002; 
     [cell.contentView addSubview:titleLabel]; 
    } 
} 

//Now we have a cell object with controls attached. 
//Now to update the contents on the control, just get the control from cell 
//using its tag and set your data from datasource 
if(indexPath.row == 0){ 
    UILabel *titleLabel = (UILabel*)[cell.contentView viewWithTag:1002]; 
    titleLabel.text = //Text from your datasource for this row 
} 

Пожалуйста, обратите внимание, что вам нужно позаботиться о высоте и в heightForRowAtIndexPath. Там же будет применена та же логика.

+0

thanx для ur help, я думаю, что это правильный путь, но проблема в том, что содержимое моих ячеек таблицы не является общим для всех ячеек, поэтому я не могу добавить их перед проверкой номера строки, и поэтому я не смогу повторно использовать ячейку. Что ты думаешь? – ViruMax

+0

Затем вы можете создавать элементы управления внутри if (cell == nil), проверяя строку. т.е. если строка == 1, тогда создайте и присоедините только изображениеView ... и в приведенном ниже коде просто используйте такое же условие, чтобы получить добавленный элемент управления. – HRM

+0

Обновлен мой ответ. Пожалуйста, проверьте и дайте мне знать, работает ли это для u. – HRM

0

Вот что я бы рекомендовал:

  1. Создание пользовательского класса UITableViewCell, и в его initWithStyle:reuseIdentifier: создать все необходимые подвиды. Вам также нужно будет присвоить свои подзоны свойствам для внешнего использования.
  2. Сообщите вашему UITableView объекту, чтобы зарегистрировать класс или NIB в viewDidLoad.
  3. В tableView:cellForRowAtIndexPath: вы можете получить доступ к свойствам ячейки и соответствующим образом обновить их.

Таким образом, вы не воссоздаете ячейку или ее подвиды каждый раз, когда вызывается tableView:cellForRowAtIndexPath:.

+0

Использование пользовательской ячейки uitableview не будет эффективным, потому что моя структура ячейки не является общей для всех ячеек. – ViruMax

0

Я рекомендую удалить подпункты из представления содержимого UITableViewCell в cellForRowAtInddexPath с помощью перечисления объектов-C. Посмотрите ниже код для справки.

for(UIView *view in cell.contentView.subviews){ 
    if ([view isKindOfClass:[UIView class]]) { 
     [view removeFromSuperview]; 
    } 
} 
Смежные вопросы