8

似乎 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;
4

3 回答 3

15

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

于 2013-09-22T15:27:33.620 回答
7

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

-(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 版本并根据每个版本实现不同的属性。

于 2013-09-30T20:16:02.900 回答
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;
}
于 2014-09-02T00:55:51.393 回答