Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIPickerView: NSAttributedString not available in iOS 7?

It seems the UIPickerView no longer supports the use of NSAttributedString for picker view items. Can anyone confirm this? I found NS_AVAILABLE_IOS(6_0) in the UIPickerView.h file, but is this the problem? Is there a way around this, or am I out of luck?

- (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;
like image 876
Rob Avatar asked Sep 22 '13 14:09

Rob


3 Answers

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.

like image 101
Rob Avatar answered Oct 31 '22 19:10

Rob


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.

like image 7
self.name Avatar answered Oct 31 '22 20:10

self.name


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;
}
like image 4
Chris Avatar answered Oct 31 '22 18:10

Chris