UIPickerView:NSAttributedString在iOS 7中不可用?

时间:2013-09-22 14:54:19

标签: ios uipickerview uipickerviewdatasource

似乎UIPickerView不再支持将NSAttributedString用于选择器视图项。谁能证实这一点?我在NS_AVAILABLE_IOS(6_0)文件中找到UIPickerView.h,但这是问题吗?有没有办法解决这个问题,还是我运气不好?

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component NS_AVAILABLE_IOS(6_0); // attributed title is favored if both methods are implemented
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view;

3 个答案:

答案 0 :(得分:14)

此问题的唯一解决方案显然是使用pickerView:viewForRow:forComponent:reusingView:并返回带有属性文本的UILabel,因为Apple显然已禁用使用属性字符串。

答案 1 :(得分:7)

Rob是对的,错误或不是在iOS 7中UIPickerView中获取属性文本的最简单方法是破解pickerView:viewForRow:forComponent:reusingView:method。这就是我做的......

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    // create attributed string
    NSString *yourString = @"a string";  //can also use array[row] to get string
    NSDictionary *attributeDict = @{NSForegroundColorAttributeName : [UIColor whiteColor]};
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:yourString attributes:attributeDict];

    // add the string to a label's attributedText property
    UILabel *labelView = [[UILabel alloc] init];
    labelView.attributedText = attributedString;

    // return the label
    return labelView;
}

在iOS 7上看起来很棒,但在iOS 6中,默认背景为白色,因此您无法看到我的白色文字。我建议检查iOS版本并根据每个版本实现不同的属性。

答案 2 :(得分:4)

以下是使用pickerView:viewForRow:forComponent:reusingView:以尊重循环视图的方式的示例。

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UILabel *)recycledLabel {
    UILabel *label = recycledLabel;
    if (!label) { // Make a new label if necessary.
        label = [[UILabel alloc] init];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentCenter;
    }
    label.text = [self myPickerTitleForRow:row forComponent:component];
    return label;
}