Прокрутка UITableView изменяет изображение внутри UITableViewCell - PullRequest
1 голос
/ 03 декабря 2009

Я отображаю некоторые данные, используя UITableViewController, моя таблица имеет 2 статических раздела с 6 статическими строками в каждом. И я делю подклассы UITableViewCell, чтобы добавить 3 метки и вид, в представлении я рисую стрелку только в одной из ячеек в одном из разделов.

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

Вот мой код:

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

static NSString *CellIdentifier = @"Cell";

TableViewCells *cell = (TableViewCells *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[TableViewCells alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[self configureCell:cell atIndexPath:indexPath];


return cell;

}

- (void)configureCell:(TableViewCells *)cell atIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.row) {
    case 0:
    {
        if (indexPath.section == cotizacionIdeal)
        {
            cell.arrowImage = [UIImage imageNamed:@"arrowUp.png"];
            [cell.nombre setText:@"Recursos"];
            [cell.cantidad setText:[NSString stringWithFormat:@"%1.2f", [cotizacionPrevia.sueldoDeRecursos doubleValue]]];
            [cell.porcentaje setText:[NSString stringWithFormat:@"%1.2f%@", [cotizacion.recursosPorcentaje doubleValue], @"%"]];
        }
        else
        {
            [cell.nombre setText:@"Recursos"];
            [cell.cantidad setText:[NSString stringWithFormat:@"%1.2f", [cotizacionPrevia.sueldoDeRecursos doubleValue]]];
            [cell.porcentaje setText:[Calculate calcPorcentaje:cotizacionPrevia.sueldoDeRecursos totalReal:self.totalReal]];
        }
    }
        break;
    case 1:
    {
        if (indexPath.section == cotizacionIdeal)
        {
            [cell.nombre setText:@"Comision de Venta"];
            [cell.cantidad setText:[Calculate calcMonto:cotizacion.comisionPorcentaje total:self.totalIdeal]];
            [cell.porcentaje setText:[NSString stringWithFormat:@"%1.2f%@", [cotizacion.comisionPorcentaje doubleValue], @"%"]];
        }
        else
        {
            [cell.nombre setText:@"Comision de Venta"];
            [cell.cantidad setText:self.montoRealComision];
            [cell.porcentaje setText:[NSString stringWithFormat:@"%1.2f%@", [cotizacion.comisionPorcentaje doubleValue], @"%"]];
        }
    }

UITableViewCell класс:

    - (id)initWithFrame:(CGRect)frame cell:(TableViewCells *)cell
{
    if (self = [super initWithFrame:frame]) {
        _cell = cell;

        //self.opaque = YES;
        //self.backgroundColor = _cell.backgroundColor;
    }

    return self;
}

- (void)drawRect:(CGRect)rect
{
    [_cell.arrowImage drawAtPoint:CGPointMake(0, 0)];
}

@end

@implementation TableViewCells

@synthesize nombre;
@synthesize porcentaje;
@synthesize cantidad;
@synthesize arrowImage;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        // Initialization code

        UILabel *nombreLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.nombre = nombreLabel;
        [nombreLabel release];
        [self.nombre setFont:[UIFont boldSystemFontOfSize:14]];
        [self.contentView addSubview:self.nombre];

        UILabel *porcentajeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.porcentaje = porcentajeLabel;
        [porcentajeLabel release];
        [self.porcentaje setFont:[UIFont italicSystemFontOfSize:10]];
        [self.contentView addSubview:self.porcentaje];

        UILabel *cantidadLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.cantidad = cantidadLabel;
        [self.cantidad setTextAlignment:UITextAlignmentRight];
        [cantidadLabel release];
        [self.cantidad setFont:[UIFont boldSystemFontOfSize:14]];
        [self.contentView addSubview:self.cantidad];

        cellContentView = [[TableViewCellContentView alloc] initWithFrame:CGRectZero cell:self];
        cellContentView.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:cellContentView];
    }

UPDATE:

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

- (void)configureCell:(TableViewCells *)cell atIndexPath:(NSIndexPath *)indexPath {
cell.arrowImage = [UIImage imageNamed:@"arrowDown.png"];
switch (indexPath.row) {
    case 0:
    {
        if (indexPath.section == cotizacionIdeal)
        {
            cell.arrowImage = [UIImage imageNamed:@"arrowUp.png"];
            [cell.nombre setText:@"Recursos"];
            [cell.cantidad setText:[NSString stringWithFormat:@"%1.2f", [cotizacionPrevia.sueldoDeRecursos doubleValue]]];
            [cell.porcentaje setText:[NSString stringWithFormat:@"%1.2f%@", [cotizacion.recursosPorcentaje doubleValue], @"%"]];
        }
        else
        {

Ответы [ 3 ]

1 голос
/ 11 декабря 2009

Проблема в том, что всякий раз, когда вы используете drawRect для ячейки, вы ДОЛЖНЫ вызывать setneedsdisplay. Вот что исправило мою проблему.

0 голосов
/ 04 декабря 2009

Я не на 100% в этом, но я думаю, что это связано с выпуском изображения. Когда вы используете imageNamed, экземпляр сохраняется, поэтому вместо него предлагается использовать imageWithFilePath.

Надеюсь, это поможет ....

0 голосов
/ 03 декабря 2009

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

Если стрелка не должна отображаться в ячейке, явно очистите ее в методе configureCell, и это должно исправить это.

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