2011-09-12 11 views
6

Tengo un UITableView indexado con secciones individuales. Me gustaría utilizar un color de fondo diferente para las vistas de encabezado en cada sección. Sé que puedo implementar mi propia visión implementando tableView: viewForHeaderInSection: (por ejemplo, vea question # 2898361), pero parece ser "demasiado trabajo" para mí: la vista estándar se ve bien, solo tendría que cambiar su fondo. color.¿Cómo puedo acceder al viewForHeaderInSection estándar para un tableView?

¿Pero cómo puedo acceder a esta vista estándar? No puedo usar [super tableView:viewForHeaderInSection:] porque se trata de implementar un protocolo y no una cuestión de herencia. ¿De otra manera puedo obtener la vista estándar?

Respuesta

13

Estoy casi seguro de que no se puede hacer esto fácilmente. Utilicé una de mis solicitudes de soporte técnico en mi cuenta de desarrollador recientemente preguntando sobre la alteración del fondo y los bordes de las secciones de UITableView. El ingeniero de Apple me dijo que esto realmente no era algo fácil de hacer, e incluso si lograras hacerlo, probablemente afectarías el rendimiento. También me señaló a cocoawithlove y un artículo sobre uitableviews edición:

http://cocoawithlove.com/2009/08/adding-shadow-effects-to-uitableview.html

En realidad, la creación de su propia cabecera no es mucho esfuerzo. A continuación se muestra un código saqué de uno de mis proyectos - se comentó a cabo, por lo que podría no funcionar de inmediato - pero se puede conseguir la idea:

- (CAGradientLayer *) greyGradient { 
    CAGradientLayer *gradient = [CAGradientLayer layer]; 
    gradient.startPoint = CGPointMake(0.5, 0.0); 
    gradient.endPoint = CGPointMake(0.5, 1.0); 

    UIColor *color1 = [UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0]; 
    UIColor *color2 = [UIColor colorWithRed:240.0f/255.0f green:240.0f/255.0f blue:240.0f/255.0f alpha:1.0]; 

    [gradient setColors:[NSArray arrayWithObjects:(id)color1.CGColor, (id)color2.CGColor, nil]]; 
    return gradient; 
} 

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    CGFloat width = CGRectGetWidth(tableView.bounds); 
    CGFloat height = [self tableView:tableView heightForHeaderInSection:section]; 
    UIView *container = [[[UIView alloc] initWithFrame:CGRectMake(0,0,width,height)] autorelease]; 
    container.layer.borderColor = [UIColor grayColor].CGColor; 
    container.layer.borderWidth = 1.0f; 
    CAGradientLayer *gradient = [self greyGradient]; 
    gradient.frame = container.bounds; 
    [container.layer addSublayer:gradient]; 

    UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectMake(12,0,width,height)] autorelease]; 
    headerLabel.backgroundColor = [UIColor clearColor]; 
    headerLabel.font= [UIFont boldSystemFontOfSize:19.0f]; 
    headerLabel.shadowOffset = CGSizeMake(1, 1); 
    headerLabel.textColor = [UIColor whiteColor]; 
    headerLabel.shadowColor = [UIColor darkGrayColor]; 
    NSString *title = [self tableView:tableView titleForHeaderInSection:section]; 
    headerLabel.text = title; 
    return container; 
} 

Asegúrese de

#import <QuartzCore/QuartzCore.h> 

Por De la manera ... esto no se supone que imite el aspecto de los encabezados estándar, es solo un ejemplo. Pero estoy seguro de que con un poco de prueba y error podría alterar esto para imitar a los estándares y luego cambiar los colores ligeramente.

+1

Parece que falta algo en su texto ... # importa qué? Probablemente algunas cosas de animación central? – Thorsten

+0

Oh sí, fue QuartzCore para usar CAGradientLayer - Lo agregaré a la publicación. Gracias – bandejapaisa

+0

También falta [container addSubview: headerLabel], y realmente es mejor si haces algo como esto: \t CGFloat width = tableView.bounds.size.width; \t CGFloat height = [self tableView: tableView heightForHeaderInSection: section]; UIView * contenedor = [[UIView alloc] initWithFrame: CGRectMake (0,0, ancho, alto)]; –

1

Hay un problema con la solución de @bandejapalsa: el separador de la celda anterior sigue siendo visible con esta implementación, ya que no está en la sección predeterminada de iOS HeaderView. La solución que encontré fue usar un CALayer y compensarlo por 1 pix. La imagen debe ser 1 píxel más alta que el marco de vista en sí.

// Create the view for the header 
CGRect aFrame =CGRectMake(0, 0, tableView.contentSize.width, IMIUICustomisation.sectionHeaderViewHeight); 
UIView * aView = [[UIView alloc] initWithFrame:aFrame]; 
aView.backgroundColor = UIColor.clearColor; 

// Create a stretchable image for the background that emulates the default gradient, only in green 
UIImage *viewBackgroundImage = [[UIImage imageNamed:@"greenheader.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0]; 

// Cannot set this image directly as the background of the cell because 
// the background needs to be offset by 1pix at the top to cover the previous cell border (Alex Deplov's requirement ^_^) 
CALayer *backgroungLayer = [CALayer layer]; 

backgroungLayer.frame = CGRectMake(0, -1, tableView.contentSize.width, IMIUICustomisation.sectionHeaderViewHeight+1); 
backgroungLayer.contents = (id) viewBackgroundImage.CGImage; 
backgroungLayer.masksToBounds = NO; 
backgroungLayer.opacity = 0.9; 
[aView.layer addSublayer:backgroungLayer]; 

// Take care of the section title now 
UILabel *aTitle = [[UILabel alloc] initWithFrame: CGRectMake(10, 0, aView.bounds.size.width-10, aView.bounds.size.height)]; 
aTitle.text = [delegate tableView:tableView titleForHeaderInSection:section]; 
aTitle.backgroundColor = UIColor.clearColor; 
aTitle.font = [UIFont boldSystemFontOfSize:18]; 
aTitle.textColor = UIColor.whiteColor; 

// Text shadow 
aTitle.layer.shadowOffset = CGSizeMake(0, 1); 
aTitle.layer.shadowRadius = .2; 
aTitle.layer.masksToBounds = NO; 
aTitle.layer.shadowOpacity = 0.5; 
aTitle.layer.shadowColor = IMIUICustomisation.selectedElementTextShadowColor.CGColor; 
[aView addSubview:aTitle]; 

return aView; 
5

Aunque las otras respuestas señalan correctamente que no se puede acceder a la vista por defecto para hacer simples modificaciones a la misma, si no tiene nada de personalizar para un encabezado de sección en particular, puede volver nil de tableView:viewForHeaderInSection: y la vista tabla usa la vista por defecto

Esto es útil si solo necesita personalizar algunos de sus encabezados.

Por alguna razón esto es undocumented.

Cuestiones relacionadas