中心UIPickerView文本

Mse*_*enb 37 iphone uipickerview iphone-sdk-3.0

所以我有一个uipickerview,其行只包含0-24号,看起来有点傻,因为数字是左对齐的,在pickerview的右边留下了巨大的空白.

有没有一种简单的方法可以在uipickerview中居中对齐文本?

Rob*_*bin 67

- (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;
}
Run Code Online (Sandbox Code Playgroud)

或类似的东西.

  • 很好,但应该重复使用视图,而不是在每次调用时创建一个新标签. (3认同)

Jam*_*her 22

现在在iOS 6中更容易一点......你可以实现一种新的方法来返回一个属性字符串......你可以在属性字符串中定义对齐方式.

- (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;
}
Run Code Online (Sandbox Code Playgroud)


Rog*_*Rog 12

您可以实现此委托方法,该方法返回CGFloat

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

在拾取器视图上调用此方法以确定行宽.


Pra*_*mar 5

下面一个也工作正常 -

- (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;
}
Run Code Online (Sandbox Code Playgroud)

干杯!!