Условное добавление изображения в пользовательское свойство cell.contentView - PullRequest
0 голосов
/ 22 октября 2011

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

Поэтому мне нужно создать пользовательское представление контента с двумя UILabel и UIImageView, как описано в «Руководстве по программированию табличного представления для iOS».

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

    YOEvento *aux = [[self.eventosListsContainer objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        // 1. Check if it is a favourtite to display the icon

        if (aux.isFavourite) {
            // Evento is favourite
            // 1. Create the main label view
            mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20, 8, 248, 14)] autorelease];
            mainLabel.tag = MAINLABEL_TAG;
            mainLabel.font = [UIFont systemFontOfSize:13.0];
            mainLabel.textColor = [UIColor darkGrayColor];
            mainLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
            [cell.contentView addSubview:mainLabel];

            // Create the date label
            secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(23, 24, 245, 11)] autorelease];
            secondLabel.tag = SECONDLABEL_TAG;
            secondLabel.font = [UIFont systemFontOfSize:11.0];
            secondLabel.textColor = [UIColor lightGrayColor];
            secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
            [cell.contentView addSubview:secondLabel];

            // Create the image
            icon = [[[UIImageView alloc] initWithFrame:CGRectMake(268, 12, 24, 21)] autorelease];
            icon.tag = ICON_TAG;
            icon.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
            [cell.contentView addSubview:icon];

        } else {
            // Evento is not favourite
            // 1. Create the main label view
            mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20, 8, 282, 14)] autorelease];
            mainLabel.tag = MAINLABEL_TAG;
            mainLabel.font = [UIFont systemFontOfSize:13.0];
            mainLabel.textColor = [UIColor darkGrayColor];
            mainLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
            [cell.contentView addSubview:mainLabel];

            // Create the date label
            secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(23, 24, 279, 11)] autorelease];
            secondLabel.tag = SECONDLABEL_TAG;
            secondLabel.font = [UIFont systemFontOfSize:11.0];
            secondLabel.textColor = [UIColor lightGrayColor];
            secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
            [cell.contentView addSubview:secondLabel];            

        }
    } else {
        // 
        if (aux.isFavourite) {
            mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
            secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
            icon = (UIImageView *)[cell.contentView viewWithTag:ICON_TAG];
        } else {
            mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
            secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];            
        }
    }

    // Load cell values

    if (aux.isFavourite) {
        mainLabel.text = aux.nombre;
        secondLabel.text = @"16 de Octubre"; // ?????????????
        icon.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"29-heart"
                                                                                      ofType:@"png"]];
    } else {
        mainLabel.text = aux.nombre;
        secondLabel.text = @"16 de Octubre"; // ????????????? 
    }    
    return cell;
}

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

В моей первоначальной реализации (с использованием свойства imageView) это было легко, я просто проверяю, не было ли событие, которое было установлено фаворитом cell.imageView = nil. Но понятия не имею, как сделать с пользовательским contentView.

1 Ответ

2 голосов
/ 22 октября 2011

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

static NSString *CellIdentifierFavourite = @"CellFavourite";
static NSString *CellIdentifierNonFavourite = @"CellNonFavourite";

//  Other setup goes here

YOEvento *aux = [[self.eventosListsContainer objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

if (aux.isFavourite) {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierFavourite];
    if (cell == nil) {
        //  Create favourite cell here
    }
    // Populate favourite cell here
} else {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierNonFavourite];
    if (cell == nil) {
        //  Create non-favourite cell here
    }
    // Populate non-favourite cell here
}

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