UIPickerView: NSAttributedString not available in iOS 7?

无人久伴 提交于 2019-11-28 01:09:48

The only solution to this problem is apparently to use pickerView:viewForRow:forComponent:reusingView: and return a UILabel with the attributed text, since Apple has apparently disabled using attributed strings otherwise.

Rob is right, bug or not the easiest way to get attributed text in a UIPickerView in iOS 7 is to hack the pickerView: viewForRow: forComponent: reusingView: method. Here's what I did...

-(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;
}

It looks great on iOS 7, but in iOS 6 the default background is white so you can't see my white text. I'd suggest checking for iOS version and implementing different attributes based on each.

Here's an example of using pickerView:viewForRow:forComponent:reusingView: in a way that honors the recycled views.

- (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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!