Потеря данных на UITableViewCell при прокрутке UITableView? - PullRequest
2 голосов
/ 23 марта 2012

Я пытаюсь реализовать приложение UITableview. В моем tableView их 10 разделов, и каждый раздел имеет один ряд. Я хочу, чтобы каждый раздел имел различный тип ContentView (1-8 одинаковых ContentView 9-й раздел Разные ContentView) Я сделал этот код для этого.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 10;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier1 = @"Cell1";
    static NSString *CellIdentifier2 = @"Cell2";
    UITextField *textField;
    UITextView *textView;
    NSUInteger section=[indexPath section];
    if(section == 9){
        UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
        //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        if(cell==nil){
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1]autorelease];
            textView=[[UITextView alloc]initWithFrame:CGRectMake(5, 5, 290, 110)];
            [textView setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor
                                          ]];
            [textView setTag:([indexPath section]+100)];
            [cell.contentView addSubview:textView];
        }else{
            textView=(UITextView*)[cell.contentView viewWithTag:([indexPath section]+100)];
        }
        return cell;
    }else {
        UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
       // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        if(cell==nil){
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2]autorelease];
            textField=[[UITextField alloc]initWithFrame:CGRectMake(5, 5, 290, 50)];
            [textField setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor]];
            [textField setTag:([indexPath section]+100)];
            [cell.contentView addSubview:textField];
        }else{
            textField=(UITextField*)[cell.contentView viewWithTag:([indexPath section]+100)];

        }

        return cell;
    }  


    return nil;

}

Моя проблема: 1. После ввода какой-то вещи в UITextField / UITextView я прокручиваю в UITableView. в это время все данные в UITableViewCell (UITextField / UITextView) были потеряны, кроме данных последней ячейки. 2. Если я создаю ячейку

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

Вместо

 UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];

Данные будут повторяться. Как я могу решить эту проблему?

Ответы [ 5 ]

9 голосов
/ 23 марта 2012

Эта строка:

UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];

Никогда не должна появляться в вашем источнике данных метод cellForRowAtIndexPath.

Кроме того, ваш код в порядке, за исключением того, что вы нигде не устанавливаете значение текстового поля.Вам нужна модель (например, массив строк для 10 значений текстового поля).Эта модель должна обновляться при редактировании текстовых полей, и в приведенном выше методе вы копируете значение обратно из модели в текстовое свойство текстового поля:

textfield.text = [self.modelArray objectAtIndex:indexPath.section];
1 голос
/ 23 марта 2012

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

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

Я предлагаю сделать это так:Теперь ваш cellForRowAtIndexPath немного проще:

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

    static NSString *CellIdentifier1 = @"Cell1";
    static NSString *CellIdentifier2 = @"Cell2";

    NSUInteger section=[indexPath section];

    if(section == 9) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        if(cell==nil) {
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1]autorelease];
        }

    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        if(cell==nil) {
            cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2]autorelease];
        }
    }  

    // who knows what subview this cell has?  it might not have one, or it might have the wrong one
    // just clean it up to be certain
    for (UIView *view in cell.subviews) {
        [view removeFromSuperView];
    }

    // get the textControl we set up for _this_ section/cell
    UIControl *textControl = [self.sections objectAtIndex:section];

    // now we have a fresh cell and the right textControl.  drop it in
    [cell addSubview:textControl];
    return cell;
}
0 голосов
/ 15 апреля 2013

У меня была такая же проблема.Это не проблема с классом таблицы.Проблема в том месте, где вы вызываете этот tableviewcontroller.Сначала сделайте объект этого вызова в .h, а затем выделите в .m, вот и все.

Когда я объявлял в viewdidload, как tbl *t = [self.storyboard...];, я также столкнулся с той же проблемой.Но когда я ставлю tbl *t; в .h проблема решена.

0 голосов
/ 23 марта 2012

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

     if (tagvalue ==3) {

        static NSString *CellIdentifier = @"Cell3";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle    
        reuseIdentifier:CellIdentifier] autorelease];
        }
        lbl7 = [[UILabel alloc] init];
         [lbl7 setFont:[UIFont boldSystemFontOfSize:20]];
         [cell.contentView addSubview:lbl7];
         lbl7.backgroundColor = [UIColor clearColor];
         lbl7.frame = CGRectMake(120, 5, 0, 40);
         lbl7.tag = 70;
         [lbl7 release];

         lbl8 = [[UILabel alloc] init];
         [lbl8 setFont:[UIFont boldSystemFontOfSize:18]];
         [cell.contentView addSubview:lbl8];
         lbl8.backgroundColor = [UIColor clearColor];
         lbl8.textColor = [UIColor grayColor];
         lbl8.frame = CGRectMake(120, 50, 0, 40);
         lbl8.tag = 80;
         [lbl8 release];

        lbl7 = (UILabel*)[cell.contentView viewWithTag:70];
        lbl8 = (UILabel*)[cell.contentView viewWithTag:80];
        lbl7.text = [[rowsarray objectAtIndex:row]objectForKey:@"name"];
        lbl8.text = [[rowsarray objectAtIndex:row]objectForKey:@"flavour"];
        [lbl7 sizeToFit];
        [lbl8 sizeToFit];

        return cell;
    }
    if (tagvalue ==4) {
        static NSString *CellIdentifier = @"Cell4";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        }
        lbl9 = [[UILabel alloc] init];
         [lbl9 setFont:[UIFont boldSystemFontOfSize:20]];
         [cell.contentView addSubview:lbl9];
         lbl9.backgroundColor = [UIColor clearColor];
         lbl9.frame = CGRectMake(120, 5, 0, 40);
         lbl9.tag = 90;
         [lbl9 release];

         lbl10 = [[UILabel alloc] init];
         [lbl10 setFont:[UIFont boldSystemFontOfSize:18]];
         [cell.contentView addSubview:lbl10];
         lbl10.backgroundColor = [UIColor clearColor];
         lbl10.textColor = [UIColor grayColor];
         lbl10.frame = CGRectMake(120, 50, 0, 40);
         lbl10.tag = 100;
         [lbl10 release];            
        lbl9 = (UILabel*)[cell.contentView viewWithTag:90];
        lbl10 = (UILabel*)[cell.contentView viewWithTag:100];
        lbl9.text = [[rowsarray objectAtIndex:row]objectForKey:@"name"];
        lbl10.text = [[rowsarray objectAtIndex:row]objectForKey:@"flavour"];
        [lbl9 sizeToFit];
        [lbl10 sizeToFit];

        return cell;
    }
0 голосов
/ 23 марта 2012

эй, причина в том, что вы делаете это, когда ячейка равна нулю? но вы не пишете код, когда ячейка не равна нулю.

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

UITableViewCell * cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier: CellIdentifier];

 UIImageView *imgView; 
   if(cell == nil)
   {
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero              reuseIdentifier:CellIdentifier] autorelease];

   imgView = [[UIImageView alloc] initWithFrame:CGRectMake(100,0,100,62)];
   [imgView setImage:[UIImage imageNamed:@"img.png"]];
   imgView.tag = 55;
   [cell.contentView addSubview:imgView];
   [imgView release];
 } 
 else
 {
    imgView = (id)[cell.contentView viewWithTag:55];
  }

чтобы показать здесь imgView = (id) [cell.contentView viewWithTag: 55]; вам нужно присвоить вам тег и написать код, показанный выше, в противном случае.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...