2012-06-25 20 views

Respuesta

9

Mediante el uso de un identificador de celda distinta para cada uno que obtendrá. Puede usar algo como esto:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *cellIdentifier = [NSString stringWithFormat:@"s%i-r%i", indexPath.section, indexPath.row]; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; 
     //you can customize your cell here because it will be used just for one row. 
    } 

    return cell; 
} 
12

Hacer celdas estáticamente programáticamente no tiene sentido. Las células estáticas son básicamente solo para Interface Builder y requieren que TableView sea entero. Le permiten arrastrar UILables, UITextFields, UIImageViews, etc. directamente a las celdas y hacer que se muestre cómo se ve en Xcode cuando se ejecuta la aplicación.

Sin embargo, sus celdas pueden ser "estáticas" programáticamente al no usar una fuente de datos externa y codificar todo en forma rígida, lo que generalmente va a ser un poco complicado y generalmente una mala idea.

Sugiero crear un nuevo UITableViewController con .xib y personalizarlo desde allí si quiere celdas "estáticas". De lo contrario, solo codifica todos tus valores y básicamente es lo mismo, pero probablemente sea un diseño deficiente si se puede evitar.

3

También podría hacerlo de la forma anterior y simplemente crear la celda de la manera que desee dependiendo del NSIndexPath, esto funciona con TVC de células estáticas y vistas de tabla regulares (no olvide devolver el número adecuado de secciones y filas en sus métodos de origen de datos):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    switch indexPath.row { 
     case 0: 
      // First cell, setup the way you want 

     case 1: 
      // First cell, setup the way you want 
    } 

    // return the customized cell 
    return cell; 
} 
1

que desea crear la estructura de las células, por ejemplo, para una pantalla de configuración o algo así, y que tal vez necesita sólo modificar algunas células contenido, pero no su número o secciones de estructura que pueden sobrecargar método de su subclase UITableViewController como este:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *aCell = [super tableView:tableView cellForRowAtIndexPath:indexPath]; 

    // Configure the cell... 
    if ([aCell.reuseIdentifier isEqualToString:@"someIdentifier"]){ 
     //some configuration block 
    } 

    else if ([aCell.reuseIdentifier isEqualToString:@"someOtherIdentifier"]) { 
     //other configuration block 
    } 
    return aCell; 
} 

Pero puede hacerlo de una mejor manera con un poco más de código;

1) En el comienzo de su archivo .m añadir typedef:

typedef void(^IDPCellConfigurationBlock)(UITableViewCell *aCell); 

2) añadir una propiedad a su extensión cellConfigurations TablviewControllerSubclass:

@interface IPDSettingsTableViewController() 

@property (nonatomic, strong) NSDictionary *cellConfigurations; 
@property (nonatomic) id dataModel; 

@end 

3) Modificar las células estáticas de TableviewController subclase en el guión gráfico o xib y agregue unique CellReuseIdentifier para cada celda que desee modificar mediante programación

4) En sus viewDidLoad instalación Método de bloques cellsConfiguration:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self SetupCellsConfigurationBlocks]; 
} 

- (void)SetupCellsConfigurationBlocks 
{ 
    //Store configurations code for each cell reuse identifier 
    NSMutableDictionary *cellsConfigurationBlocks = [NSMutableDictionary new];   


    //store cells configurations for a different cells identifiers 
    cellsConfigurationBlocks[@"someCellIdentifier"] = ^(UITableViewCell *aCell){ 
     aCell.backgroundColor = [UIColor orangeColor]; 
    }; 

    cellsConfigurationBlocks[@"otherCellIdentifier"] = ^(UITableViewCell *aCell){ 
     aCell.imageView.image = [UIImage imageNamed:@"some image name"]; 
    }; 

    //use waek reference to self to avoid memory leaks 
    __weak typeof (self) weakSelf = self; 
    cellsConfigurationBlocks[@"nextCellIdentifier"] = ^(UITableViewCell *aCell){ 
     //You can even use your data model to configure cell 
     aCell.textLabel.textColor = [[weakSelf.dataModel someProperty] isEqual:@YES] ? [UIColor purpleColor] : [UIColor yellowColor]; 
     aCell.textLabel.text  = [weakSelf.dataModel someOtherProperty]; 
    }; 
    weakSelf.cellConfigurations = [cellsConfigurationBlocks copy]; 
} 

5) sobrecargue tableView: Método cellForRowAtIndexPath así:

#pragma mark - Table view data source 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *aCell = [super tableView:tableView cellForRowAtIndexPath:indexPath]; 

    // configure cell 
    [self configureCell:aCell withConfigurationBlock:self.cellConfigurations[aCell.reuseIdentifier]]; 
    return aCell; 
} 

- (void)configureCell:(UITableViewCell *)aCell withConfigurationBlock:(IDPCellConfigurationBlock)configureCellBlock 
{ 
    if (configureCellBlock){ 
     configureCellBlock(aCell); 
    } 
} 
0

Es bastante normal que desee construir una tabla sencilla de usar como una menú o formulario, pero el uso de la API integrada con el origen de datos y las devoluciones de llamadas delegadas no hace que sea fácil de escribir o mantener. Es posible que necesites agregar/eliminar/actualizar dinámicamente algunas celdas, por lo que usar Storyboards por sí solo no funcionará.

Puse juntos MEDeclarativeTable para construir programáticamente tablas pequeñas.Proporciona el origen de datos y el delegado para UITableView. Terminamos con una API donde proporcionamos instancias de secciones y filas en lugar de implementar métodos de fuente de datos y delegar.

Cuestiones relacionadas