UIPickerView: NSAttributedString не доступен в iOS 7?

Похоже, 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 ответа

Решение

Единственное решение этой проблемы, по-видимому, заключается в использовании pickerView:viewForRow:forComponent:reusingView: и вернуть UILabel с атрибутивным текстом, поскольку Apple явно отключила использование атрибутивных строк.

Роб прав, ошибся или нет. Самый простой способ получить атрибутированный текст в UIPickerView в iOS 7 - это взломать 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 и реализовать различные атрибуты на основе каждого из них.

Вот пример использования 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;
}
Другие вопросы по тегам