2009-12-03 2 views
1

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

Все это прекрасно. Пока я не прокручу вниз ... тогда стрелка случайно помещается в другие ячейки, как только я прокручу назад, стрелка снова изменила ячейки ... Это также происходит, если я попытаюсь установить 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 
     { 

ответ

1

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

0

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

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

+0

Привет, Бен, спасибо за ваш ответ. Я знаю, что ячейки просмотра повторно используются, и я попытался явно очистить свойство cell.arrowImage, установив его на ноль. Однако это плохо работает. Даже если я устанавливаю разные изображения для каждой отдельной ячейки, как только я прокручиваю вниз и вверх, изображения смешиваются. Я устанавливаю свои изображения в каждой ячейке так же, как и устанавливаю их в первом. Как мне решить эту проблему ?. Заранее спасибо. -Oscar –

+0

Я также попытался это Подход - (Недействительными) configureCell: (TableViewCells *) клетка atIndexPath: (NSIndexPath *) indexPath { \t cell.arrowImage = [UIImage imageNamed: @ "arrowDown.png"]; \t переключатель (indexPath.row) { \t \t Случай 0: \t \t { \t \t \t, если (indexPath.раздел == cotizacionIdeal) \t \t \t { \t \t \t \t cell.arrowImage = [UIImage imageNamed: @ "arrowUp.png"]; \t \t \t \t [cell.nombre setText: @ "Recursos"]; \t \t \t \t [cell.cantidad setText: [NSString stringWithFormat: @ "% 1.2f", [cotizacionPrevia.sueldoDeRecursos doubleValue]]]; Что работает нормально, пока я не прокручу вниз и вверх. –

+0

Мне интересно, может быть, это потому, что я использую симулятор iphone? –

0

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

Надеется, что это помогает ....

Смежные вопросы