UITableViewCell Content View - Добавление UILabels - PullRequest
3 голосов
/ 14 января 2011

У меня в настоящее время есть следующий код для моего cellForRowAtIndexPath на моем UITableView:

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

    static NSString* CellIdentifier = @"Cell";
    UILabel* nameLabel = nil;
    UILabel* valueLabel = nil;
    UILabel *percentLabel = nil;

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
    if ( cell == nil ) 
    {
        inthere = YES;
        cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault 
                                       reuseIdentifier: CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        nameLabel = [[[UILabel alloc] initWithFrame:CGRectMake( 7.0, 0.0, 140.0, 44.0 )] autorelease];
        nameLabel.tag = 21;
        nameLabel.font = [UIFont systemFontOfSize: 12.0];
        nameLabel.textAlignment = UITextAlignmentLeft;
        nameLabel.textColor = [UIColor darkGrayColor];
        nameLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
        nameLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview: nameLabel];

        valueLabel = [[[UILabel alloc] initWithFrame: CGRectMake( 165.0, 0.0, 80, 44.0 )] autorelease];
        valueLabel.tag = 22;
        valueLabel.font = [UIFont systemFontOfSize: 11];
        valueLabel.textAlignment = UITextAlignmentRight;
        valueLabel.textColor = [UIColor blueColor];
        valueLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
        valueLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview: valueLabel];

        percentLabel = [[[UILabel alloc] initWithFrame: CGRectMake(245, 0.0, 65, 44.0 )] autorelease];
        percentLabel.tag = 24;
        percentLabel.font = [UIFont systemFontOfSize: 12];
        percentLabel.textAlignment = UITextAlignmentRight;
        percentLabel.textColor = [UIColor blueColor];
        percentLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
        percentLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview: percentLabel];
    }
    else
    {
        nameLabel = (UILabel*)[cell.contentView viewWithTag:21];
        valueLabel = (UILabel*)[cell.contentView viewWithTag:22];
        percentLabel = (UILabel *)[cell.contentView viewWithTag:24];
    }

   ...and then I initialize the text of each of these three labels...

}

Но я хотел бы, чтобы эти три метки были разных цветов в зависимости отклетка.Например, все ячейки в разделе 3 должны иметь красный nameLabels, а все ячейки в разделе 5 должны иметь зеленый valueLabels.Но если я вставлю это в код после того, как инициализирую текст всех меток:

if(indexPath.section==3) {
    nameLabel.textColor = [UIColor redColor];
}
if(indexPath.section==5) {
    valueLabel.textColor = [UIColor greenColor];
}

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

Как я могу указать цвета этих трех меток для каждой отдельной ячейки в моей таблице?

Ответы [ 3 ]

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

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

if(indexPath.section==3)
    nameLabel.textColor = [UIColor redColor];
else
    nameLabel.textColor = [UIColor blackColor];

Кстати, ваша ячейка выглядит настолько сложной, что я бы порекомендовал создать ее с помощью Interface Builder.

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

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

Попробуйте это,

if (indexPath.section == 3) {

    nameLabel.textColor = [UIColor redColor];
    nameLabel.frame = CGRectMake(someX, someY, someWidth, someHeight);
    valueLabel.textColor = [UIColor blackColor];
    valueLabel.frame = CGRectMake(someX, someY, someWidth, someHeight);
}

if (indexPath.section == 5) {

    nameLabel.textColor = [UIColor blackColor];
    nameLabel.frame = CGRectMake(someX, someY, someWidth, someHeight);
    valueLabel.textColor = [UIColor greenColor];
    valueLabel.frame = CGRectMake(someX, someY, someWidth, someHeight);
}
0 голосов
/ 14 января 2011

Ваш код выглядит нормально. Единственное, что я могу предложить попробовать, это не использовать autorelease для меток и вместо release каждый сразу после добавления в contentView.

...