2011-02-06 16 views

Respuesta

10

Personalmente, creo que ambos tutoriales sugeridos tienen un gran defecto cuando se trata de reuseIdentifier. Si olvida asignarlo en el constructor de la interfaz o lo escribe mal, cargará la punta cada vez que se llame a cellForRowAtIndexPath.

Jeff LaMarche escribe sobre esto y cómo solucionarlo en este blog post. Además de reuseIdentifier usa el mismo enfoque que en la documentación de apple en Loading Custom Table-View Cells From Nib Files.

Después de haber leído todos estos artículos que se me ocurrió siguiente código:

Editar: Si el idioma de iOS 5.0 y superior que querrá seguir con Duane Fields' answer

@interface CustomCellWithXib : UITableViewCell 

+ (NSString *)reuseIdentifier; 
- (id)initWithOwner:(id)owner; 

@end 

@implementation CustomCellWithXib 

+ (UINib*)nib 
{ 
    // singleton implementation to get a UINib object 
    static dispatch_once_t pred = 0; 
    __strong static UINib* _sharedNibObject = nil; 
    dispatch_once(&pred, ^{ 
     _sharedNibObject = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil]; 
    }); 
    return _sharedNibObject; 
} 

- (NSString *)reuseIdentifier 
{ 
    return [[self class] reuseIdentifier]; 
} 

+ (NSString *)reuseIdentifier 
{ 
    // return any identifier you like, in this case the class name 
    return NSStringFromClass([self class]); 
} 

- (id)initWithOwner:(id)owner 
{ 
    return [[[[self class] nib] instantiateWithOwner:owner options:nil] objectAtIndex:0]; 
} 

@end 

UINib (disponible en iOS 4.0 y posterior) se usa aquí como singleton, porque aunque se usa reuseIdentifier, la celda aún se reinicializa unas 10 veces más o menos. Ahora cellForRowAtIndexPath se parece a esto:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CustomCellWithXib *cell = [tableView dequeueReusableCellWithIdentifier:[CustomCellWithXib reuseIdentifier]]; 
    if (cell == nil) { 
     cell = [[CustomCellWithXib alloc] initWithOwner:self]; 
    } 

    // do additional cell configuration 

    return cell; 
} 
+0

En mi opinión, es la mejor manera. Gracias por esto. Si fuera mi tema, lo marcaría como respuesta. –

15

En IOS5 que querrá utilizar el nuevo:

registerNib:forCellReuseIdentifier:

Lo que básicamente hace lo mismo ...

+0

Genial, no lo he notado. ¡Gracias! – christoph

+0

¡Eso es lo que estaba tratando de recordar! Bonito. – Ash

+1

Más específicamente, agréguelo a su viewDidLoad: [self.tableView registerNib: [UINib nibWithNibName: @ paquete "CustomCell": nil] forCellReuseIdentifier: @ "CustomCell"]; –

0

Puede crear Clase CustomCell con XIB que se hereda de UITableViewCell. Agregaremos la categoría en el archivo .m de la clase tableview de la siguiente manera. Creo que este es el método más fácil que se puede aplicar para la creación de celdas personalizadas.

 

    @interface UITableViewCell(NIB) 
    @property(nonatomic,readwrite,copy) NSString *reuseIdentifier; 
    @end 
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     return 30; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
    static NSString *[email protected]"cell"; 
     CustomCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier]; 
     if(cell==nil) 
     { 
      NSLog(@"New Cell"); 
      NSArray *nib=[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil]; 
      cell=[nib objectAtIndex:0]; 
      cell.reuseIdentifier=identifier; 

     }else{ 
      NSLog(@"Reuse Cell"); 
     } 
     cell.lbltitle.text=[NSString stringWithFormat:@"Level %d",indexPath.row]; 
     id num=[_arrslidervalues objectAtIndex:indexPath.row]; 
     cell.slider.value=[num floatValue]; 
     return cell; 
    } 
    @end 

1

`Puede crear celdas personalizadas en la vista de tabla con la ayuda del archivo .xib. Primero configure la vista de tabla en su controlador de vista, cree un nuevo archivo xib con su clase y úselo en la vista de tabla.

- (IBAction)moveToSubCategory:(id)sender; 
@property (strong, nonatomic) IBOutlet UILabel *foodCategoryLabel; 
@property (strong, nonatomic) IBOutlet UIImageView *cellBg; 



-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [foodCatArray count]; 
} 



-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     static NSString *simpleTableIdentifier = @"ExampleCell"; 
     ExampleCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
     if (cell == nil) { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ExampleCell" owner:self options:nil]; 
     cell = [nib objectAtIndex:0]; 
    } 
    [cell setTag:indexPath.row]; 
    cell.cellBg.image=[UIImage imageNamed:[photoArray objectAtIndex:indexPath.row]]; 
    cell.foodCategoryLabel.text=[foodCatArray objectAtIndex:indexPath.row]; 
    return cell; 

} 
Cuestiones relacionadas