更改不同列的UIPickerView字体大小

时间:2015-01-21 21:25:10

标签: ios iphone uipickerview

我正在构建一个UIPickerView,它可以正常使用我的代码。

//Title for Row
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    if (component==kNumComponent)
        return Number[row];
        else if(component==kSeaComponent)
            return Season[row];
        else
            return Course[row];

}

其中Number,Season和Course是存储字符串的NSArray。在这里,我想将字体大小更改为较小的字体。我在这里学到了一些例子。

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row
forComponent:(NSInteger)component reusingView:(UIView *)view {
            UILabel *retval = (id)view;
            if (!retval) {
                retval= [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)] autorelease];
            }

            retval.font = [UIFont systemFontOfSize:22];
            retval.text = [pickerViewArray objectAtIndex:row];
       return retval;
    }

我有没有快速的方法将上面的代码组合到我的可用代码中来改变字体大小?说,我想需要通过" Retval"某处?

更新:感谢Scotts的提示(见下文),我的方法有效,发布在这里:

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

    UILabel *retval = (UILabel*)view;
    if (!retval) {
        retval = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)];
    }

    retval.font = [UIFont systemFontOfSize:22];

    if (component==kNumComponent)
        retval.text = Number[row];
    else if(component==kSeaComponent)
    {retval.font = [UIFont systemFontOfSize:14];
        retval.text = Season[row];}
    else
    { retval.font = [UIFont systemFontOfSize:14];
        retval.text = Course[row];}

    return retval;
}

1 个答案:

答案 0 :(得分:7)

要自定义您的选择器视图,您必须使用pickerView:viewForRow:。要执行此操作,请完全删除pickerView:titleForRow:,并在pickerView:viewForRow:内使用retval中最初使用的条件设置pickerView:titleForRow:的文本。

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

        UILabel *retval = (UILabel*)view;
        if (!retval) {
            retval = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)];
        }

        retval.font = [UIFont systemFontOfSize:22];

        if (component==kNumComponent)
            retval.text = Number[row];
        else if(component==kSeaComponent)
            retval.text = Season[row];
        else
            retval.text = Course[row];

        return retval;
}

或者,您可以使用UIPickerViewDelegate的{​​{1}}方法直接编辑标题的字体,而不是创建标签子视图,例如:

pickerView:attributedTitleForRow:forComponent: