Cuando llega el campo vacío, ¿eliminó la fila en la vista de mesa agrupada en iPhone?

StackOverflow https://stackoverflow.com/questions/4793198

  •  24-10-2019
  •  | 
  •  

Pregunta

He mostrado los datos en la vista de tabla agrupada. Los datos se muestran en la vista de tabla desde el análisis XML. Tengo 2 sección de la vista de la tabla, la sección uno tiene tres filas y la sección dos tiene dos filas.

  section 1 ->  3 Rows

  section 2 - > 2 Rows.

Ahora quiero verificar, si alguien de la cadena está vacía, entonces debería quitar las celdas vacías, por lo que he enfrentado algunos problemas, si he eliminado cualquier celda vacía, entonces cambiará el número de índice. Entonces, ¿cómo puedo comprobar que alguien del campo está vacío?, Porque algunas veces se vendrá más número de campo vacío, de modo que la posición del índice cambie. Entonces, por favor envíeme algún código de muestra o enlace para eso. ¿Cómo puedo conseguir esto?

Código de muestra,

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section       
 {

 if (section == 0) {

    if([userEmail isEqualToString:@" "] || [phoneNumber isEqualToString:@" "] || [firstName isEqualToString:@" "])
    {
        return 2;

    } 

    else {

        return 3;

    }
}
if (section == 1) {

       if(![gradYear isEqualToString:@" "] || ![graduate isEqualToString:@" "]) {

    return 1;
}
    else
   {
        return 2;
     }


return 0;

}

¡¡¡Por favor, ayúdame!!!

Gracias.

¿Fue útil?

Solución

Según tengo entendido, no desea agregar la fila donde los datos están vacíos, por lo que sugeriré que debe perprar los datos de las secciones antes de contar la vista de la tabla sobre las secciones y las filas.

Por lo tanto, puede ser el siguiente código puede ayudarlo ..., lo he probado, solo necesita llamar al método "preparareSectionData" desde el método "ViewDidload" y definir las matrices de sección en el archivo .h.

- (void) prepareSectionData {
 NSString *userEmail = @"";
 NSString *phoneNumber = @"";
 NSString *firstName = @"";

 NSString *gradYear = @"";
 NSString *graduate = @"";

 sectionOneArray = [[NSMutableArray alloc] init];
 [self isEmpty:userEmail]?:[sectionOneArray addObject:userEmail];
 [self isEmpty:phoneNumber]?:[sectionOneArray addObject:phoneNumber];
 [self isEmpty:firstName]?:[sectionOneArray addObject:firstName];

 sectionTwoArray = [[NSMutableArray alloc] init];
 [self isEmpty:gradYear]?:[sectionTwoArray addObject:gradYear];
 [self isEmpty:graduate]?:[sectionTwoArray addObject:graduate];
}

 -(BOOL) isEmpty :(NSString*)str{
 if(str == nil || [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)
     return YES;
 return NO;
 }

  // Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(section == 0){
    return [sectionOneArray count];
} else if (section == 1) {
    return [sectionTwoArray count];
}
return 0;
}


// Customize the appearance of table view cells.

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



static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell.
if(indexPath.section == 0){
    cell.textLabel.text = [sectionOneArray objectAtIndex:indexPath.row];
} else if (indexPath.section == 1) {
    cell.textLabel.text = [sectionTwoArray objectAtIndex:indexPath.row];
}
return cell;
}

Otros consejos

@Pugal Devan, bueno, puede mantener los datos en una matriz, pero el problema en ese caso es que debe cuidar los límites de la matriz y corregir índices para diferentes secciones. Para cada sección, IndExpath.row comenzará desde el índice 0, y si sus datos están en una sola matriz, debe administrar el índice de fila por usted mismo. Pero aún así, si quieres conservarlo, puedes hacerte:

int sectionOneIndex = 0; 
int sectionTwoIndex = 3;
NSMutableArray *sectionArray = [[NSMutableArray alloc] initWithObjects:@"email", @"Name", @"address", @"zipCode", @"country", nil];

Por encima de dos enteros representa la posición inicial de los elementos de sus diferentes secciones. Los primeros 3 objetos de la matriz de sección son la parte de la sección uno, y los últimos dos objetos son la parte de la sección dos. Ahora necesita devolver el recuento de filas correctos. Por eso puede escribir:

if(section == 0) return [sectionArray count] - (sectionTwoIndex-1); //returns 3
else if(section == 1) return [sectionArray count] - sectionTwoIndex; //returns 2

O si su recuento es estático, puede poner valores constantes a cambio.

Y en el momento en que lea de Array, simplemente agregará este índice en el valor de fila, que devolverá la posición correcta de su elemento para la celda actual.

// Customize the appearance of table view cells.

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

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell.
if(indexPath.section == 0){
cell.textLabel.text = [sectionArray objectAtIndex:indexPath.row + sectionOneIndex];
} else if (indexPath.section == 1) {
cell.textLabel.text = [sectionArray objectAtIndex:indexPath.row + sectionTwoIndex];
}
return cell;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top