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;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With