在UIPickerView中包装文本

时间:2014-10-31 13:29:23

标签: ios ios7 uipickerview

我有一个UIPickerView,其中没有显示全文。它最终会被截断。

如何以2行或更多行显示文字?

我尝试了以下代码,但它仍然以单行显示,并且它不是完整的文本。

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    // Fill the label text here
    NSString *title = @"";

    UILabel* tView = (UILabel*)view;
    if (!tView){
        CGRect frame = CGRectZero;
        tView = [[UILabel alloc] initWithFrame:frame];
        [tView setFont:[UIFont fontWithName:@"Helvetica" size:15]];
        tView.minimumScaleFactor = 9.0f;
        tView.adjustsFontSizeToFitWidth = YES;
        tView.numberOfLines = 2;

        [tView setText:title];
        [tView setTextAlignment:NSTextAlignmentLeft];
    }

    return tView;
}

1 个答案:

答案 0 :(得分:1)

当我通过使用UIFont创建类别类将自定义字体设置为应用程序时,UIPickerView中的文本显示为两行。

@implementation UIFont (CustomFont)

+(UIFont *)regularFontWithSize:(CGFloat)size
{
    return [UIFont fontWithName:GOATHAM_FONT size:size];
}

+(UIFont *)boldFontWithSize:(CGFloat)size
{
    return [UIFont fontWithName:GOATHAM_FONT size:size];
}

+(void)load
{
    SEL original = @selector(systemFontOfSize:);
    SEL modified = @selector(regularFontWithSize:);
    SEL originalBold = @selector(boldSystemFontOfSize:);
    SEL modifiedBold = @selector(boldFontWithSize:);

    Method originalMethod = class_getClassMethod(self, original);
    Method modifiedMethod = class_getClassMethod(self, modified);
    method_exchangeImplementations(originalMethod, modifiedMethod);

    Method originalBoldMethod = class_getClassMethod(self, originalBold);
    Method modifiedBoldMethod = class_getClassMethod(self, modifiedBold);
    method_exchangeImplementations(originalBoldMethod, modifiedBoldMethod);
}

@end

另外,我在UIPickerView委托方法中设置了字体。

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

    NSString *title = @"";

    UILabel* tView = (UILabel*)view;
    if (!tView){
        CGRect frame = CGRectZero;
        tView = [[UILabel alloc] initWithFrame:frame];
        [tView setFont:[UIFont fontWithName:GOATHAM_FONT size:14]];
        tView.minimumScaleFactor = 9.0f;
        tView.adjustsFontSizeToFitWidth = YES;
        tView.numberOfLines = 2;

        [tView setText:title];
        [tView setTextAlignment:NSTextAlignmentLeft];
    }

    return tView;
}

执行此操作后,文本在UIPickerView中以两行显示。