2012-10-01 24 views
12

Estoy trabajando en una aplicación donde se requiere que la sección Encabezado de la sección esté a la derecha en lugar de la izquierda predeterminada.UITableView encabezado de sección a la derecha en lugar de predeterminado a la izquierda

Busqué y muchos geeks propuestas para aplicar:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    static UIView *headerView; 

    if (headerView != nil) 
     return headerView; 

    NSString *headerText = NSLocalizedString(@"البحث الأخيرة", nil); 

    // set the container width to a known value so that we can center a label in it 
    // it will get resized by the tableview since we set autoresizeflags 
    float headerWidth = 150.0f; 
    float padding = 10.0f; // an arbitrary amount to center the label in the container 

    headerView = [[UIView alloc] initWithFrame:CGRectMake(300, 0.0f, headerWidth, 44.0f)]; 
    headerView.autoresizingMask = UIViewAutoresizingFlexibleWidth; 

    // create the label centered in the container, then set the appropriate autoresize mask 
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, 0, headerWidth - 2.0f * padding, 44.0f)]; 
    headerLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin; 
    headerLabel.textAlignment = UITextAlignmentRight; 
    headerLabel.text = headerText; 

    [headerView addSubview:headerLabel]; 

    return headerView; 
} 

Sin embargo, cuando intento de aumentar la coordenada x del punto de vista del marco de cabecera, que no afecta a la posición de la vista. Y siempre está en el centro de la vista de tabla.

Necesito que el encabezado esté a la derecha.

+0

En vez de ir con un flexibleWidth, no se puede lo fuerza a ser ancho? Entonces la vista consumirá todo el ancho y justificará el texto a la derecha. – bryanmac

+0

Ya seleccionó una respuesta que es en su mayoría correcta, pero agregar espacios para obtener un margen es un truco real. La forma correcta de resolver su problema es crear una vista vacía (o una con un color de fondo) y usarla como headerView. Luego agrega un UILabel a esa vista de contenedor y lo compensa un poco desde el lado derecho. Este concepto - usar una vista vacía como contenedor para colocar otras vistas es una herramienta común y útil. –

+0

@DavidH tienes razón. La idea de agregar espacios no es buena. Aunque funcionó para mí por el momento.Como mencioné en mi pregunta, la vista siempre estaba en el centro, donde lo necesitaba a la derecha. Establecer el marco no funcionaba. También la etiqueta estaba alineada a la derecha. Entiendo que usar una UIView es mucho mejor tener más opciones de personalización. ¡Gracias por el comentario! –

Respuesta

15

Esto funcionó para mí, sin embargo jugar con las coordenadas del marco para alinear de acuerdo a sus necesidades

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    UILabel *label = [[UILabel alloc] init]; 
    [email protected]"header title"; 
    label.backgroundColor=[UIColor clearColor]; 
    label.textAlignment = NSTextAlignmentRight; 
    return label; 
} 

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section 
{ 
    return 50; 
} 
+1

sí corregimos suponiendo que UILabel es una subclase de uiview –

+1

¡Gracias! Funcionó :). Sin embargo, el comienzo del texto casi tocaba el borde de la vista. Agregué algunos espacios al texto y ahora el texto se desplaza un poco hacia la izquierda. –

+3

'UITextAlignmentRight' está en desuso, debe usar' NSTextAlignmentRight' –

0

firt de todo lo que no sería inicializar el UIView con

headerView = [[UIView alloc] initWithFrame:CGRectMake(300, 0.0f, headerWidth, 44.0f)]; 

Desde su origen de coordenadas x será 300.For cabecera y footerviews establecen su origen de coordenadas a CGPoint (0.0) y sólo jugar con el tamaño.

Intente hacer que la etiqueta sea tan grande como la vista y ajuste su alineación a la derecha.

UIView *headerTitleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)]; 

UILabel *sectionTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, headerTitleView.frame.size.width, 40)]; 
sectionTitleLabel.backgroundColor = [UIColor clearColor]; 
sectionTitleLabel.textAlignment = UITextAlignmentright; 

Otra posibilidad es agregar una UIlabel en algún lugar en el lado derecho de la vista de encabezado con la alineación central.

0

No estoy seguro de entender la situación, pero estoy asumiendo que lo que desea el la etiqueta se alineará a la derecha en lugar de a la izquierda.

Ajustar el valor de marco para su vista de encabezado no funcionará porque el tableView es responsable de posicionarlo e ignorará los valores que establezca aquí.

Su única opción es trabajar con las subvistas de headerView.

ejemplo, el establecimiento de su posición headerLabel a estar alineado a la derecha:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    static UIView *headerView; 

    if (headerView != nil) 
     return headerView; 

    NSString *headerText = NSLocalizedString(@"البحث الأخيرة", nil); 

    float headerWidth = 320.0f; 
    float padding = 10.0f; 

    headerView = [[UIView alloc] initWithFrame:CGRectMake(300, 0.0f, headerWidth, 44.0f)]; 
    headerView.autoresizesSubviews = YES; 

    // create the label centered in the container, then set the appropriate autoresize mask 
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, headerWidth, 44.0f)]; 
    headerLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth; 
    headerLabel.textAlignment = UITextAlignmentRight; 
    headerLabel.text = headerText; 

    CGSize textSize = [headerText sizeWithFont:headerLabel.font constrainedToSize:headerLabel.frame.size lineBreakMode:UILineBreakModeWordWrap]; 
    headerLabel.frame = CGRectMake(headerWidth - (textSize.width + padding), headerLabel.frame.origin.y, textSize.width, headerLabel.frame.size.height); 

    [headerView addSubview:headerLabel]; 

    return headerView; 
} 
+0

la alineación ya está configurada a la derecha. –

7

que tenía problemas para cambiar el texto con la solución anterior, esto funcionó para mí y para lugares con espacio apropiado con el borde de salida de la vista de tabla Solución PS en Swift

UITableViewDataSource

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    return 30 
} 

UITAbleViewDelegate

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return "Header Title" 
} 

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { 

    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView 
    header.textLabel?.font = UIFont(name: "AvenirNext-Regular", size: 14.0) 
    header.textLabel?.textAlignment = NSTextAlignment.Right 

} 
Cuestiones relacionadas