2011-02-18 21 views
36

Así que tengo un uipickerview con filas que solo contienen el número 0-24 y parece un poco tonto ya que los números se dejan alineados dejando un gran espacio a la derecha de la vista de selección.Center UIPickerView Text

¿Hay una manera fácil de centrar el texto en un uipickerview?

+1

Todavía se verá tonto si los números están centrados. ¿Cuales son los numeros? ¿Por qué no escribir, por ejemplo, "24 horas" en lugar de "24"? Puede ser redundante pero se ve mejor. –

+0

@fluchtpunkt En realidad, es una buena idea ... se ve bastante mejor – Msencenb

Respuesta

66
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view 
{ 
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)]; 
    label.text = [NSString stringWithFormat:@"something here"]; 
    label.textAlignment = NSTextAlignmentCenter; //Changed to NS as UI is deprecated. 
    label.backgroundColor = [UIColor clearColor]; 
    [label autorelease]; 
    return label; 
} 

o algo así.

+1

También uso esto para cambiar el color de fuente en función de qué fila es, como esta: if (fila == 0) { [label setTextColor: [UIColor redColor]]; } else { [label setTextColor: [UIColor darkTextColor]]; } – Structurer

+0

¿Ahora el texto no está en negrita? – To1ne

+1

Por defecto, el texto en un UIPicker está en negrita. Con este enfoque, debe agregar la línea 'label.font = [UIFont boldSystemFontOfSize: [UIFont labelFontSize]];' para obtener una apariencia similar. – To1ne

3

Ninguna propiedad del selector que tenga la capacidad de alineación establecida.

por lo que necesita un código para esto.

ver el código

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { 

    return 1; 
} 


- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component 
{ 
    return 25; 

} 

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { 

NSString *title=[NSString stringWithFormat:@"   %i",row];//here you give extra spaces. 
    return title; 
} 
11

Puede implementar este método delegado, que devuelve un CGFloat

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component

esto se le llama en la vista selector para determinar el ancho de fila.

+1

De hecho, utilicé esta técnica para hacer que el selector sea más pequeño ... Creo que se ve mejor que simplemente centrar. Dicho esto, voy a marcar la subclase uiview como la respuesta correcta, ya que el título original era sobre centrar en un UIPickerView ... pero tu respuesta es muy útil también. Upvoted. – Msencenb

+0

¡Muchas gracias por este consejo! Resulta que iOS 7 ignorará 'widthForComponent' si configura el marco de la vista de selección después de' viewDidLoad'. iOS 6, OTOH, redimensionará en parte (ver http://i.imgur.com/UDLaDYO.png) la vista de selección de acuerdo con 'widthForComponent', y en parte de acuerdo con el marco de la vista. Mi solución fue no implementar 'widthForComponent', solo configurar el marco pickerview. – thomax

3

Recuerde, la vista en

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view 

es en realidad un UITableViewCell, para que pueda trabajar con él como:

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view 
{ 
    static NSString *cellIdentifier = @"pickerViewCell"; 
    UITableViewCell *cell = (UITableViewCell*)view; 

    if(cell==nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; 
     /** customize the cell **/ 
    } 

    /** set the label **/ 
    cell.textLabel.text = [dataSource objectAtIndex:row]; 

    return cell; 
} 
+2

Con ese método delegado puede devolver cualquier UIView que desee. En la respuesta aceptada, se sugiere usar un UILabel simple y establecer la alineación de texto para centrar. Eso funciona. Pero si desea algo diferente, como una lista de minutos en una columna centrada, pero para que sus bordes derechos se alineen (no simplemente centrados), entonces una UITableViewCell presentada a su gusto es una excelente sugerencia. +1 –

21

un poco más fácil ahora en iOS 6 ... Hay un nuevo método puede implementar para devolver una cadena atribuida ... Y puede definir la alineación en cadenas atribuidas.

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component { 
    NSString *text = [NSString stringWithFormat:@"R%d C%d", row, component]; 
    NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:text]; 
    NSMutableParagraphStyle *mutParaStyle=[[NSMutableParagraphStyle alloc] init]; 
    mutParaStyle.alignment = NSTextAlignmentCenter; 
    [as addAttribute:NSParagraphStyleAttributeName value:mutParaStyle range:NSMakeRange(0,[text length])]; 
    return as; 
} 
+0

Gracias, esto funciona, pero dang es un PitA. También vale la pena señalar que esto reemplazará cualquier cosa que se devuelva de 'pickerView: titleForRow: forComponent:'. Lo que hice fue copiar mi código de ese método y reemplazar mi 'return's con' text = ', y eso parece estar funcionando. – GeneralMike

4

A continuación también se trabaja bien -

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view 
{ 
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)]; 
    lbl.text = [reservePickerArray objectAtIndex:row]; 
    lbl.adjustsFontSizeToFitWidth = YES; 
    lbl.textAlignment=UITextAlignmentCenter; 
    lbl.font=[UIFont systemFontOfSize:20]; 
    return lbl; 
} 

Saludos !!

0

Sé que esta pregunta no está etiquetada para rápida, pero en caso de que alguien esté buscando la versión de Swift 3.0, aquí está.

/* Called by the picker view when it needs the view to use for a given row in  
a given component. If the previously used view (the view parameter) is adequate,  
return that. If you return a different view, the previously used view is  
released. The picker view centers the returned view in the rectangle for row.  

*/ 
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { 

    var label = UILabel(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(300), height: CGFloat(37))) 


    let booking = self.bookingInfo[row] //bookingInfo is an array of elements 
     label.text = String(booking.BookingNumber) + String(booking.DateAndTime) 
     label.textAlignment = .left 
     return label 
}