2011-01-12 10 views
12

Mi aplicación utiliza abreviaturas en títulos de encabezado de sección UITableView que son difíciles de pronunciar para VoiceOver. Como necesito hacer que estos títulos sean pronunciables por VoiceOver, necesito darle un título de encabezado de sección a accessibilityLabel.Cómo imitar el estilo de encabezado de sección UITableViewStylePlain de UITableView

Parece que la única forma de hacerlo es dibujar una celda de encabezado de sección personalizada. Me gustaría imitar el estilo estándar proporcionado por Apple UIKit para estos encabezados de sección personalizados, pero no estoy seguro de cómo emular el aspecto detallado de Apple de este elemento.

¿Cuál es el mejor enfoque para imitar el estilo de encabezado de la sección UITableViewStylePlain?

Actualización: Soy muy consciente de cómo crear una celda de encabezado personalizada. Lo que estoy buscando es una técnica para imitar exactamente el aspecto del estilo de celda del encabezado proporcionado por Apple para las celdas del encabezado de la sección sencilla UITableView.

Respuesta

0

Crearía una clase UIView personalizada y le agregaría un UILabel para el texto del encabezado de sección. Para el fondo, use un UIImageView y cargue la imagen apropiada para el fondo del encabezado de la sección. Asigna este UIImageView con el método addSubView: para tu UIView.

En UITableViewController puede establecer tableView.sectionHeaderHeight para personalizar el alto de todos los encabezados de sección. Utilizando el método UITableViewDelegate:

tableView:viewForHeaderInSection: 

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITableViewDelegate

Usted debe devolver una instancia de su UIView personalizado con la etiqueta de texto como título de la sección.

Debe agregar una sombra al UILabel y ajustar todos los colores para adaptarlos al estilo predeterminado. Desde encabezados de sección son también ligeramente transparente, puede configurar su alfa UIView con

self.alpha = 0.9f; 
+0

Sé cómo implementar mi propia celda de cabecera que es bastante sencilla. Sin embargo, me gustaría imitar exactamente el aspecto del estilo de encabezado de sección predeterminado para el UITableView simple proporcionado por Apple. Actualizaré mi pregunta para aclarar esto. – Bringo

+0

Si quisiera imitarlo exactamente no estoy seguro, ya que son objetos UIView y no una clase especial propia. –

+0

¿Ha mirado este protocolo informal: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIAccessibility_Protocol/Introduction/Introduction.html –

11

Si alguien sigue interesado, tengo que mirar muy muy estrecha con el siguiente código (usando imágenes de Mark Adams del comentario anterior , pero les cambia el tamaño un poco como mi aplicación también cuenta con el modo horizontal):

- (UIView *)tableView:(UITableView *)tbl viewForHeaderInSection:(NSInteger)section 
{ 
    UIView* sectionHead = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tbl.bounds.size.width, 18)]; 
    sectionHead.backgroundColor = [UIColor colorWithWhite:0 alpha:0]; 
    sectionHead.userInteractionEnabled = YES; 
    sectionHead.tag = section; 

    UIImageView *headerImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"PlainTableViewSectionHeader.png"]]; 
    headerImage.contentMode = UIViewContentModeScaleAspectFit; 

    [sectionHead addSubview:headerImage]; 
    [headerImage release]; 

    UILabel *sectionText = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, tbl.bounds.size.width - 10, 18)]; 
    sectionText.text = text; 
    sectionText.backgroundColor = [UIColor clearColor]; 
    sectionText.textColor = [UIColor whiteColor]; 
    sectionText.shadowColor = [UIColor darkGrayColor]; 
    sectionText.shadowOffset = CGSizeMake(0,1); 
    sectionText.font = [UIFont boldSystemFontOfSize:18]; 

    [sectionHead addSubview:sectionText]; 
    [sectionText release]; 

    return [sectionHead autorelease]; 
} 
8

Esto es una implementación de una subclase UILabel que imita el fondo programáticamente:

UITableViewStandardHeaderLabel.h

#import <UIKit/UIKit.h> 

@interface UITableViewStandardHeaderLabel : UILabel 

@property (nonatomic) CGFloat topInset; 
@property (nonatomic) CGFloat leftInset; 
@property (nonatomic) CGFloat bottomInset; 
@property (nonatomic) CGFloat rightInset; 

@end 

UITableViewStandardHeaderLabel.m:

/*! 
* @class UITableViewStandardHeaderLabel 
* @brief Reimplementation of the UILabel used for a standard UITableView's group headers for customization purposes 
*/ 

@implementation UITableViewStandardHeaderLabel 

@synthesize topInset, leftInset, bottomInset, rightInset; 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 

    if (self) { 
     self.backgroundColor = [UIColor clearColor]; 
    } 

    return self; 
} 

- (void)drawTextInRect:(CGRect)rect 
{ 
    UIEdgeInsets insets = {self.topInset, self.leftInset, self.bottomInset, self.rightInset}; 

    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)]; 
} 

- (void)drawRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGGradientRef backgroundGradient; 
    CGColorSpaceRef rgbColorspace; 
    size_t num_locations = 2; 
    CGFloat locations[2] = { 0.0f, 1.0f }; 
    CGFloat components[8] = { 144.0f/255.0f, 159.0f/255.0f, 171.0f/255.0f, 1.0f, 
           /* start */ 183.0f/255.0f, 192.0f/255.0f, 200.0f/255.0f, 1.0f /* end */ }; 

    rgbColorspace = CGColorSpaceCreateDeviceRGB(); 
    backgroundGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations); 

    CGRect currentBounds = self.bounds; 
    CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMinY(currentBounds)); 
    CGPoint bottomCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds)); 

    CGContextDrawLinearGradient(context, backgroundGradient, topCenter, bottomCenter, 0); 

    UIColor *topBorderLineColor = [UIColor colorWithRed:113.0f/255.0f green:125.0f/255.0f blue:133.0f/255.0f alpha:1.0]; 
    UIColor *secondLineColor = [UIColor colorWithRed:165.0f/255.0f green:177.0f/255.0f blue:187.0f/255.0f alpha:1.0]; 
    UIColor *bottomBorderLineColor = [UIColor colorWithRed:151.0f/255.0f green:157.0f/255.0f blue:164.0f/255.0f alpha:1.0]; 

    [topBorderLineColor setFill]; 
    CGContextFillRect(context, CGRectMake(0, 0, CGRectGetMaxX(currentBounds), 1)); 

    [bottomBorderLineColor setFill]; 
    CGContextFillRect(context, CGRectMake(0, CGRectGetMaxY(currentBounds)-1, CGRectGetMaxX(currentBounds), 1)); 

    [secondLineColor setFill]; 
    CGContextFillRect(context, CGRectMake(0, 1, CGRectGetMaxX(currentBounds), 1)); 

    [super drawRect:rect]; 
} 

@end 
+0

Justo lo que estaba buscando. No puedo creer que esto no haya tenido más votos! – Baza207

1

me encontré con que las otras respuestas, o bien no funcionan o no imitan el aspecto estándar. Aquí está el mío, que funciona para iOS 5 y 6.

Tenga en cuenta que si tiene iOS 6, debe usar dequeueReusableHeaderFooterViewWithIdentifier, lo que hace las cosas mucho más fáciles y más limpias.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    if ([tableView respondsToSelector:@selector(dequeueReusableHeaderFooterViewWithIdentifier:)]) 
    { 
     static NSString *headerReuseIdentifier = @"TableViewSectionHeaderViewIdentifier"; 
     UITableViewHeaderFooterView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerReuseIdentifier]; 
     if(sectionHeaderView == nil){ 
      sectionHeaderView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:headerReuseIdentifier]; 
     } 

     //customise the label here: 
     //[sectionHeaderView.textLabel setTextColor:[UIColor whiteColor]]; 

     return sectionHeaderView; 
    } 
    else 
    {    
     UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44.0)]; 

     UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(20.0, 10, 290, 0)]; 
     headerLabel.backgroundColor = [UIColor clearColor]; 
     headerLabel.text = [self tableView:tableView titleForHeaderInSection:section]; 
     headerLabel.font = [UIFont boldSystemFontOfSize:17]; 
     headerLabel.textAlignment = NSTextAlignmentLeft; 
     headerLabel.shadowColor = [UIColor clearColor]; 
     headerLabel.numberOfLines = 0; 
     [headerLabel sizeToFit]; 
     [headerView setFrame:CGRectMake(headerView.frame.origin.x, headerView.frame.origin.y, headerView.frame.size.width, headerLabel.bounds.size.height)]; 

     //some customisation: 
     headerLabel.textColor = [UIColor whiteColor]; 

     [headerView addSubview: headerLabel]; 

     return headerView; 
    } 
} 

Como dicen los documentos, si se implementa viewForHeaderInSection también debe implementar heightForHeaderInSection.Implementarlo de esta manera para asegurarse de que obtiene el tamaño correcto para cualquier número de líneas:

-(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { 
    return UITableViewAutomaticDimension; 
} 
+0

Para cualquier persona que se tropiece con esta pregunta, si registerClass: forHeaderFooterViewReuseIdentifier: se llama, p. en viewDidLoad, luego dequeueReusableHeaderFooterViewWithIdentifier: siempre devolverá una vista y se puede omitir la siguiente prueba para nil. – Matt

Cuestiones relacionadas