Pregunta

Tengo una vista de uable y he creado una celda personalizada para mostrar mi tabla. Tengo 6 uilables que se muestran y, aunque solo tengo 20 registros para mostrar, es muy lento cuando me despliegue.

Así es como mi - TableView: CellforrowatIndExpath: parece:

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

    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";

    HistoryCell *cell = (HistoryCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];

    if (cell == nil) { 
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"HistoryCell" owner:nil options:nil];

        for (id oneObject in nib)
            if ([oneObject isKindOfClass:[UITableViewCell class]])
                cell = (HistoryCell *) oneObject;
    }

    NSArray *object;
    object = [cours objectForKey: [NSString stringWithFormat:@"%d", indexPath.section]];
    History *rowData = [object objectAtIndex:indexPath.row];

    if (rowData.month == 99) {
        cell.hour.frame = CGRectMake(10, 0, 135, 35);
        cell.data.hidden = YES;
        cell.hour.textColor = [UIColor blackColor];
        cell.hour.font = [UIFont fontWithName:@"Verdana" size:17];
    } else {
        cell.data.hidden = NO;
        cell.hour.frame = CGRectMake(10, 16, 135, 19);
        cell.hour.textColor = [UIColor grayColor];
        cell.hour.font = [UIFont fontWithName:@"Verdana" size:12];
    }

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"d (EEEE)"];
    [formatter setLocale:self.selectedLanguageLocale];
    NSString *stringFromDate = [formatter stringFromDate:rowData.data];
    [formatter release];

    cell.data.text = stringFromDate;
    cell.hour.text = rowData.ora;

    float Var1  = [rowData.Var2 floatValue];
    float Var2  = [rowData.Var2 floatValue];

    cell.R1.text = [self floatToStringFormat: [rowData.R1 floatValue]];
    cell.R2.text = [self floatToStringFormat: [rowData.R2 floatValue]];

    if (Var1 <= 0) {
        cell.Var1.textColor = [UIColor greenColor];
    } else {
        cell.Var1.textColor = [UIColor redColor];
    }
    if (Var2 <= 0) {
        cell.Var2.textColor = [UIColor greenColor];
    } else {
        cell.Var2.textColor = [UIColor redColor];
    }
    cell.Var1.text = [self floatToStringFormat:Var1];
    cell.Var2.text = [self floatToStringFormat:Var2];

    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

La razón para correr tan lento en el desplazamiento es por todas las cosas que estoy haciendo aquí (nsdateFormatter, CGMakerect, FloatToStringFormat ...) o hay algo malo en reutilizar las células?

FloatToStringFormat es una función para formatear un número a 4 decimales:

- (NSString *)floatToStringFormat:(float)number{
    NSNumberFormatter *myFloat = [[NSNumberFormatter alloc] init]; 
    [myFloat setFormatterBehavior:NSNumberFormatterBehavior10_4]; 
    [myFloat setNumberStyle:NSNumberFormatterDecimalStyle];
    [myFloat setRoundingMode:NSNumberFormatterRoundHalfUp];
    [myFloat setMinimumFractionDigits:4];
    [myFloat setMaximumFractionDigits:4];
    NSString *res = [myFloat stringFromNumber:[NSNumber numberWithFloat:number]];
    [myFloat release];
    return res;
}
¿Fue útil?

Solución

Crear y configurar los objetos de formateador es una operación costosa, por lo que comenzaría a reutilizar sus objetos de formateador, ya que son los mismos en cada llamada de función. Por lo tanto, hágales variables estáticas o variables instantáneas en su clase de origen de datos y cree la siguiente manera:

//static variable case
NSDateFormatter *formatter = nil;
if (!formatter){
   formatter = [[NSDateFormatter alloc] init];
   [formatter setDateFormat:@"d (EEEE)"];
   [formatter setLocale:self.selectedLanguageLocale];
}
NSString *stringFromDate = [formatter stringFromDate:rowData.data];
...

Otros consejos

En primer lugar, está utilizando dos identificadores diferentes: CustomCellIdentifier y BanciHistoryCellIdentifier.

En segundo lugar, ¿realmente necesitas hacer todo después? NSArray *object; ¿Cada vez que se muestra una nueva celda? Porque si no lo haces, debes moverlo al if (cell == nil) { bloquear.

Desde mi experiencia, el dibujo de las celdas de la vista de tabla se ralentiza significativamente si tiene tres o más subvistas (aunque también depende del dispositivo y las vistas). Intente dibujar directamente el contenido en DrawRect: en lugar de usar subvistas, esto debería acelerar las cosas.

Qué estás haciendo aquí:

if (cell == nil) { 
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"HistoryCell" owner:nil options:nil];

        for (id oneObject in nib)
            if ([oneObject isKindOfClass:[UITableViewCell class]])
                cell = (HistoryCell *) oneObject;
    }

Ve a leer el documentación sobre cómo hacer esto correctamente. En segundo lugar, si esto tarda demasiado en convertir las fechas y los números en cadenas, almacene los valores de cadena en su lugar, y conviértalos en valores cuando necesite modificarlas.

¿Tiene el INTERFACE BUILDER del INTERFACE? Debe coincidir exactamente con lo que está utilizando en el código. Establezca un punto de interrupción donde carga la celda de la punta y asegúrese de que esté reutilizando las celdas cuando se desplaza.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top