грязный UITableViewCell с развернуть / свернуть - PullRequest
0 голосов
/ 14 апреля 2011

Я пытаюсь реализовать ячейку просмотра таблицы раскрытия / сворачивания, как объяснено здесь . Моя модификация состоит в том, что я хочу, чтобы это было полное развернутое / свернутое табличное представление. Таким образом, каждый раздел может быть свернут / расширен. Я посмотрел на пример Apple, и он кажется излишним.

Проблема, с которой я сталкиваюсь в настоящее время, связана главным образом с проблемами форматирования и цвета. Функциональность вроде бы в порядке. Я хотел, чтобы заголовок раздела имел белый фон, а строки - синий фон. Вот мой код:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    if (dimension.selectedSegmentIndex == 0){
       if (!indexPath.row)
          {
              cell.textLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:18];
              cell.textLabel.text = [timeslot objectAtIndex:indexPath.section];
              if ([expandedSections containsIndex:indexPath.section])
              {
                  cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
              }
              else
              {
                  cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
              }
          }
          else
          {
              // all other rows
              cell.contentView.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
              cell.textLabel.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
              cell.textLabel.font = [UIFont fontWithName:@"Arial" size:14];
              cell.textLabel.textColor = [UIColor whiteColor];
              NSArray *listItems = [[timeslot objectAtIndex:indexPath.section] componentsSeparatedByString:@":"];
              if (indexPath.row == 1){
                  cell.textLabel.text = [NSString stringWithFormat:@"%@:00 - %@:15", [listItems objectAtIndex:0], [listItems objectAtIndex:0]];
              }
              if (indexPath.row == 2){
                 cell.textLabel.text = [NSString stringWithFormat:@"%@:15 - %@:30", [listItems objectAtIndex:0], [listItems objectAtIndex:0]];
              }
              if (indexPath.row == 3){
                 cell.textLabel.text = [NSString stringWithFormat:@"%@:30 - %@:45", [listItems objectAtIndex:0], [listItems objectAtIndex:0]];
              }
              if (indexPath.row == 4){
                  cell.textLabel.text = [NSString stringWithFormat:@"%@:45 - %d:00", [listItems objectAtIndex:0], ([[listItems objectAtIndex:0] intValue] + 1)];
              }

            }

        }


    if (dimension.selectedSegmentIndex == 1){
        Discount * discount = [tableData objectAtIndex:indexPath.row];
        cell.textLabel.text = discount.vendor; 
    }

    return cell;
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [manager loadObjectsAtResourcePath:@"/route.json" objectClass:[Location class] delegate: self];

    RouteMapViewController * routemap = [[RouteMapViewController alloc] initWithNibName:@"RouteMapViewController" bundle:nil];
    UIBarButtonItem *backButton =    [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                      style: UIBarButtonItemStyleBordered
                                      // style: UIBarButtonItemStylePlain
                                      // style: UIBarButtonItemStyleDone
                                                                     target:nil
                                                                     action:nil];
    self.navigationItem.backBarButtonItem = backButton;
    [backButton release];

    if (dimension.selectedSegmentIndex == 0){
            if (!indexPath.row)
            {
                // only first row toggles expand/collapse
                [preference deselectRowAtIndexPath:indexPath animated:YES];

                NSInteger section = indexPath.section;
                BOOL currentlyExpanded = [expandedSections containsIndex:section];
                NSInteger rows;

                NSMutableArray *tmpArray = [NSMutableArray array];

                if (currentlyExpanded)
                {
                    rows = [self tableView:preference numberOfRowsInSection:section];
                    [expandedSections removeIndex:section];

                }
                else
                {
                    [expandedSections addIndex:section];
                    rows = [self tableView:preference numberOfRowsInSection:section];
                }


                for (int i=1; i<rows; i++)
                {
                    NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i 
                                                                   inSection:section];
                    [tmpArray addObject:tmpIndexPath];
                }

                UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

                if (currentlyExpanded)
                {
                    [preference deleteRowsAtIndexPaths:tmpArray 
                                     withRowAnimation:UITableViewRowAnimationTop];

                    cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];

                }
                else
                {
                    [preference insertRowsAtIndexPaths:tmpArray 
                                     withRowAnimation:UITableViewRowAnimationTop];
                    cell.accessoryView =  [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];

                }
            }

     }

Вот как я ожидаю, что он будет выглядеть (шрифт раздела неправильный, так как я установил Arial Bold, но его здесь нет)

enter image description here

Вот что я получаю при расширении нижней части:

enter image description here

Этот беспорядок начал происходить после того, как я прокрутил UITableView, чтобы развернуть более позднюю запись ... Я думаю, это связано с обновлением представления ..

Ответы [ 2 ]

0 голосов
/ 14 апреля 2011

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

Например, cell.accessoryView - это то, что произошло в прошлый раз, когда ячейка использовалась в последний раз. Попробуйте установить его как ноль.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    // Creating NEW cell
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}

// Now you are using either NEW or OLD cell
// You MUST set each cell property that can be different

// code to customize cell for certain purpose

return cell;

}

В зависимости от раздела и строки вы, кажется, устанавливаете cell.textLabel.font, cell.textLabel.text, cell.accessoryView, cell.contentView.backgroundColor, cel.textLabel.backgroundColor и т. Д.

Повторное использование ячейки означает, что иногда вы получаете старую ячейку, КАК ЭТО БЫЛО ИСПОЛЬЗОВАНО в прошлый раз . Поэтому вам нужно установить все те значения, которые вы установили ранее. Если некоторые значения всегда одинаковы, определите их только один раз при создании новой ячейки ветви.

Да, это много работы. Вы можете изменить все эти длинные предложения if для переключения случаев, начать использовать предопределенные массивы, доступ к которым осуществляется через индексы, и, возможно, XIB Interface Builder для разных ячеек. Вы также можете использовать несколько разных cellIdentifiers для разных типов ячеек, если хотите. В этом случае повторное использование менее проблематично, но проще ошибаться ...

0 голосов
/ 14 апреля 2011

Чтобы внести изменения в внешний вид строк, вы должны изменить их в методе cellForRowAtIndexPath. внести соответствующие изменения в этот метод.

для изменения заголовка для tableView вы можете использовать следующий код ...

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{


        UIView *tempView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
        [tempView setBackgroundColor:[UIColor whiteColor]];
        UILabel *tempLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 44)];
        [tempLabel setBackgroundColor:[UIColor clearColor]];
        [tempLabel setTextColor:[UIColor blackColor]];
        [tempLabel setFont:[UIFont boldSystemFontOfSize:16.0]];
        [tempLabel setText:[sectionTitles objectAtIndex:section]];
        [tempView addSubview:tempLabel];
        [tempLabel release];
        return [tempView autorelease];

}

Спасибо

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