uitableviewcell example ios objective-c swift uitableview

ios - example - uitableview swift 4



Personalizar la sección del encabezado de UITableView (20)

¿Por qué no usar UITableViewHeaderFooterView ?

Quiero personalizar el encabezado UITableView para cada sección. Hasta ahora, he implementado

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

este método UITabelViewDelegate . Lo que quiero hacer es obtener un encabezado actual para cada sección y simplemente agregar UILabel como una subvista.

Hasta ahora, no soy capaz de lograr eso. Porque no pude encontrar nada para obtener el encabezado de sección predeterminado. Primera pregunta, ¿hay alguna manera de obtener encabezado de sección predeterminado ?

Si no es posible, necesito crear una vista de contenedor que sea una UIView pero, esta vez, necesito establecer el color de fondo, el color de sombra predeterminado, etc. Porque si miras detenidamente el encabezado de la sección, ya está personalizado.

¿Cómo puedo obtener estos valores predeterminados para cada encabezado de sección?

Gracias a todos.


Esta es la solución más fácil posible. El siguiente código se puede usar directamente para crear un encabezado de sección personalizado.

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { SectionHeaderTableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:@"sectionHeader"]; //For creating a drop menu of rows from the section //==THIS IS JUST AN EXAMPLE. YOU CAN REMOVE THIS IF-ELSE.== if (![self.sectionCollapsedArray[section] boolValue]) { headerView.imageView.image = [UIImage imageNamed:@"up_icon"]; } else { headerView.imageView.image = [UIImage imageNamed:@"drop_icon"]; } //For button action inside the custom cell headerView.dropButton.tag = section; [headerView.dropButton addTarget:self action:@selector(sectionTapped:) forControlEvents:UIControlEventTouchUpInside]; //For removing long touch gestures. for (UIGestureRecognizer *recognizer in headerView.contentView.gestureRecognizers) { [headerView.contentView removeGestureRecognizer:recognizer]; [headerView removeGestureRecognizer:recognizer]; } return headerView.contentView; }

NOTA: SectionHeaderTableViewCell es una UITableViewCell personalizada creada en Storyboard.


La respuesta seleccionada usando tableView :viewForHeaderInSection: es correcta.

Solo para compartir un consejo aquí.

Si está usando storyboard / xib, puede crear otra celda prototipo y usarla para su "celda de sección". El código para configurar el encabezado es similar a cómo se configura para las celdas de fila.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *HeaderCellIdentifier = @"Header"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HeaderCellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HeaderCellIdentifier]; } // Configure the cell title etc [self configureHeaderCell:cell inSection:section]; return cell; }


La versión Swift de Lochana Tejas responde:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 18)) let label = UILabel(frame: CGRectMake(10, 5, tableView.frame.size.width, 18)) label.font = UIFont.systemFontOfSize(14) label.text = list.objectAtIndex(indexPath.row) as! String view.addSubview(label) view.backgroundColor = UIColor.grayColor() // Set your background color return view }


Las otras respuestas hacen un buen trabajo al recrear la vista de encabezado predeterminada, pero en realidad no responden a su pregunta principal:

¿hay alguna forma de obtener encabezado de sección predeterminado?

Hay una manera: simplemente implemente tableView:willDisplayHeaderView:forSection: en su delegado. La vista del encabezado predeterminado se pasará al segundo parámetro, y desde allí puede convertirlo a UITableViewHeaderFooterView y luego agregar / cambiar las subvistas según lo desee.

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view; // Do whatever with the header view... }


Prueba esto......

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { // Background view is at index 0, content view at index 1 if let bgView = view.subviews[0] as? UIView { // do your stuff } view.layer.borderColor = UIColor.magentaColor().CGColor view.layer.borderWidth = 1 }


Puedes intentar esto:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)]; /* Create custom view to display section header... */ UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)]; [label setFont:[UIFont boldSystemFontOfSize:12]]; NSString *string =[list objectAtIndex:section]; /* Section header is in 0th index... */ [label setText:string]; [view addSubview:label]; [view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color... return view; }


Si headerInSection no se muestra, puede intentar esto.

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 45; }

Esto devuelve una altura para el encabezado de una sección determinada.


Si solo desea agregar título al encabezado tableView, no agregue una vista. En veloz 3.x el código es así:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var lblStr = "" if section == 0 { lblStr = "Some String 1" } else if section == 1{ lblStr = "Some String 2" } else{ lblStr = "Some String 3" } return lblStr }

Puede implementar una matriz para obtener el título de los encabezados.


Si usa la vista de encabezado predeterminada, solo puede cambiar el texto en ella con

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

Para Swift:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

Si desea personalizar la vista, necesita crear una nueva usted mismo.


Si yo fuera tú, haría un método que devuelva un UIView dado un NSString para contener. Por ejemplo

+ (UIView *) sectionViewWithTitle:(NSString *)title;

En la implementación de este método, cree un UIView, agréguele un UILabel con las propiedades que desea establecer y, por supuesto, establezca el título del mismo.


Swift 3 versión de lochana y estemendoza responde:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.size.width, height:18)) let label = UILabel(frame: CGRect(x:10, y:5, width:tableView.frame.size.width, height:18)) label.font = UIFont.systemFont(ofSize: 14) label.text = "This is a test"; view.addSubview(label); view.backgroundColor = UIColor.gray; return view }

Además, tenga en cuenta que TAMBIÉN tiene que implementar:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 100; }


Use tableView: willDisplayHeaderView: para personalizar la vista cuando está a punto de mostrarse.

Esto le da la ventaja de poder tomar la vista que ya se creó para la vista de encabezado y extenderla, en lugar de tener que volver a crear la vista de encabezado completo usted mismo.

Aquí hay un ejemplo que colorea la sección del encabezado según un BOOL y agrega un elemento de texto de detalle al encabezado.

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { // view.tintColor = [UIColor colorWithWhite:0.825 alpha:1.0]; // gray // view.tintColor = [UIColor colorWithRed:0.825 green:0.725 blue:0.725 alpha:1.0]; // reddish // view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0]; // pink // Conditionally tint the header view BOOL isMyThingOnOrOff = [self isMyThingOnOrOff]; if (isMyThingOnOrOff) { view.tintColor = [UIColor colorWithRed:0.725 green:0.925 blue:0.725 alpha:1.0]; } else { view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0]; } /* Add a detail text label (which has its own view to the section header… */ CGFloat xOrigin = 100; // arbitrary CGFloat hInset = 20; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xOrigin + hInset, 5, tableView.frame.size.width - xOrigin - (hInset * 2), 22)]; label.textAlignment = NSTextAlignmentRight; [label setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0] label.text = @"Hi. I''m the detail text"; [view addSubview:label]; }


Volviendo a la pregunta original (4 años más tarde), en lugar de reconstruir su propio encabezado de sección, iOS simplemente puede llamarlo (con willDisplayHeaderView: forSection :) justo después de que se creó el predeterminado. Por ejemplo, quería agregar un botón de gráfico en el borde derecho del encabezado de sección:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { UITableViewHeaderFooterView * header = (UITableViewHeaderFooterView *) view; if (header.contentView.subviews.count > 0) return; //in case of reuse CGFloat rightEdge = CGRectGetMaxX(header.contentView.bounds); UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(rightEdge - 44, 0, 44, CGRectGetMaxY(header.contentView.bounds))]; [button setBackgroundImage:[UIImage imageNamed:@"graphIcon"] forState:UIControlStateNormal]; [button addTarget:self action:@selector(graphButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; [view addSubview:button]; }



la solución de @samwize en Swift (¡así lo votó!). Brillante utilizando el mismo mecanismo de reciclaje también para las secciones de encabezado / pie de página:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let settingsHeaderSectionCell:SettingsHeaderSectionCell = self.dequeueReusableCell(withIdentifier: "SettingsHeaderSectionCell") as! SettingsHeaderSectionCell return settingsHeaderSectionCell }


llama a este método delegado

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ return @"Some Title"; }

esto le dará la oportunidad de agregar automáticamente un encabezado predeterminado con título dinámico.

Puede usar encabezado / pie de página reutilizable y personalizable.

https://github.com/sourov2008/UITableViewCustomHeaderFooterSection


Agrega mágicamente el encabezado de vista de tabla en forma rápida

Recientemente probé esto.

Necesitaba un solo encabezado en todo UITableView.

Como si quisiera un UIImageView en la parte superior de TableView. Así que agregué un UIImageView en la parte superior de UITableViewCell y automáticamente se agregó como tableViewHeader. Ahora conecto el ImageView al ViewController y agregué la imagen.

Estaba confundido porque hice algo como esto por primera vez. Así que, para despejar mi confusión, abra el formato xml de MainStoryBoard y encuentre que la Vista de imagen se agregó como encabezado.

Funcionó para mí Gracias xCode y swift.


- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { if([view isKindOfClass:[UITableViewHeaderFooterView class]]){ UITableViewHeaderFooterView *headerView = view; [[headerView textLabel] setTextColor:[UIColor colorWithHexString:@"666666"]]; [[headerView textLabel] setFont:[UIFont fontWithName:@"fontname" size:10]]; } }

Si desea cambiar la fuente de la etiqueta de texto en el encabezado de su sección, desea hacerlo en willDisplayHeaderView. Para configurar el texto, puede hacerlo en viewForHeaderInSection o titleForHeaderInSection. ¡Buena suerte!


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { //put your values, this is part of my code UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30.0f)]; [view setBackgroundColor:[UIColor redColor]]; UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 150, 20)]; [lbl setFont:[UIFont systemFontOfSize:18]]; [lbl setTextColor:[UIColor blueColor]]; [view addSubview:lbl]; [lbl setText:[NSString stringWithFormat:@"Section: %ld",(long)section]]; return view; }