tableview: данные перекрываются при удалении строки - PullRequest
1 голос
/ 28 декабря 2011

В моем приложении для iPhone ...

В табличном представлении я удаляю строку ...

обновление массива, из которого я подаю таблицу ....

Перезагрузка в строку данных ....

enter image description here

х

Да, но удаляемые данные верны ..

Ячейка для строки на пути индекса ....

Я только что добавил одну метку в строку ... При удалении строки

Я просто удаляю данные из массива

И обновление количества строк (уменьшение) ...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
            static NSString *CellIdentifier = @"Cell";

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


            //Get the Log Id for the sections. From Section Array
            int logID=0;
            if(indexPath.row==0)
            {
                NSLog(@"Time Array %@",timeArray);
                  logID=[[[sectionArray objectAtIndex:indexPath.section] valueForKey:@"logID"] intValue];
                  NSPredicate *p=[NSPredicate predicateWithFormat:@"logID==%d",logID];
                  fillRows=nil;
                  fillRows= [[timeArray filteredArrayUsingPredicate:p] mutableCopy];
            }

        //Show Current Time.
        //"If condition for not to go for Array Index Out of Bound".
        if(indexPath.row<[fillRows count])
        {
        //Log CurrentTime    
            cell.textLabel.text=[[fillRows objectAtIndex:indexPath.row] valueForKey:@"logCurrentTime"];
        //Log Duration.   
            UILabel *lblDuration=[[[UILabel alloc] initWithFrame:CGRectMake(110, 11, 60, 21)] autorelease] ;

      lblDuration.text=[[fillRows objectAtIndex:indexPath.row] valueForKey:@"logDuration"];
            [cell.contentView addSubview:lblDuration];
        }

            return cell;
        }

РЕДАКТИРОВАТЬ :: Вопрос о наложении ярлыков, который был решительно решен. Потому что теперь ярлык не перекрывается, а Когда я удаляю любую строку, метка этих строк остается прежней ---> последняя строка не отображается в таблице.

См. Эту ссылку Ответ

Ответы [ 3 ]

1 голос
/ 28 декабря 2011

Это потому, что dequeueReusableCellWithIdentifier возвращает неиспользованную ячейку, созданную вами из предыдущего вызова, делегату cellForRow.... Если вы собираетесь добавить метку в ячейку, вы должны сделать это после строки ячейки init и включить метку для метки, чтобы мы могли найти метку позже в ячейке. Код должен быть что-то вроде

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UILabel *lblDuration= [cell.contentView viewWithTag:1];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        lblDuration=[[[UILabel alloc] initWithFrame:CGRectMake(110, 11, 60, 21)] autorelease] ;
        lblDuration.tag = 1;
        [cell.contentView addSubview:lblDuration];
    }


    //Get the Log Id for the sections. From Section Array
    int logID=0;
    if(indexPath.row==0)
    {
         NSLog(@"Time Array %@",timeArray);
          logID=[[[sectionArray objectAtIndex:indexPath.section] valueForKey:@"logID"] intValue];
          NSPredicate *p=[NSPredicate predicateWithFormat:@"logID==%d",logID];
          fillRows=nil;
          fillRows= [[timeArray filteredArrayUsingPredicate:p] mutableCopy];
    }

    // Show Current Time.
    //"If condition for not to go for Array Index Out of Bound".
    if(indexPath.row<[fillRows count])
    {
    //Log CurrentTime    
        cell.textLabel.text=[[fillRows objectAtIndex:indexPath.row] valueForKey:@"logCurrentTime"];
    //Log Duration.   


        lblDuration.text=[[fillRows objectAtIndex:indexPath.row] valueForKey:@"logDuration"];

    }
    return cell;
}

Извините, что я не пытался скомпилировать это, но оно должно работать.

1 голос
/ 28 декабря 2011

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

попробуйте переместить следующий код в if (cell == nil) {..} block

UILabel *lblDuration=[[[UILabel alloc] initWithFrame:CGRectMake(110, 11, 60, 21)] autorelease] ;
[cell.contentView addSubview:lblDuration];
0 голосов
/ 06 января 2012

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

, поэтому просто обработайте метод удаления строки ячейки, если вы используете его для удаления .... и в этом методе также удалите UILabel ... или просто используйте [tableView reload]данные .. которые будут делать это автоматически ....

Счастливое кодирование ..:)

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