Как изменить шрифт текста в UIPickerView в iOS 7?

Я смог изменить цвет шрифта, но мне также нужно изменить размер шрифта, как я могу это сделать? Вот мой код для изменения цвета,

 - (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString *title = _currencyName[row];
    NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];

    return attString;
 }

ОБНОВЛЕНИЕ: это не сработало:

 NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light" size:40]}];

person user3121912    schedule 20.12.2013    source источник


Ответы (7)


Вот версия Swift, протестированная на iOS8:

Обновите Swift для iOS8, вы можете добавить это к своему делегату:

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {

    var pickerLabel = view as? UILabel;

    if (pickerLabel == nil)
    {
        pickerLabel = UILabel()

        pickerLabel?.font = UIFont(name: "Montserrat", size: 16)
        pickerLabel?.textAlignment = NSTextAlignment.Center
    }

    pickerLabel?.text = fetchLabelForRowNumber(row)

    return pickerLabel!;
}
person Richard Bown    schedule 19.07.2015

Обновлено для Swift 4:

public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let label = view as? UILabel ?? UILabel()
    label.font = .systemFont(ofSize: 16)
    label.textColor = .white
    label.textAlignment = .center
    label.text = text(for: row, for: component)
    return label
}
person Christopher Pickslay    schedule 21.12.2017

Вам нужно реализовать метод pickerView:viewForRow:forComponent:reusingView: в делегате сборщика

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* lbl = (UILabel*)view;
    // Customise Font 
    if (lbl == nil) {
          //label size
          CGRect frame = CGRectMake(0.0, 0.0, 70, 30);

          lbl = [[UILabel alloc] initWithFrame:frame];

          [lbl setTextAlignment:UITextAlignmentLeft];

          [lbl setBackgroundColor:[UIColor clearColor]];
           //here you can play with fonts
          [lbl setFont:[UIFont fontWithName:@"Times New Roman" size:14.0]];

   }
      //picker view array is the datasource
   [lbl setText:[pickerViewArray objectAtIndex:row]];


        return lbl;
}
person the1pawan    schedule 20.12.2013

Вы можете использовать следующий код, чтобы установить шрифт pickerview.

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *tView = (UILabel *)view;
    if (!tView){
        tView = [[UILabel alloc] init];
        [tView setFont:[UIFont .....]];//set font 
            // Setup label properties - frame, font, colors etc
            ...
    }
    // Fill the label text here
    ...
    return tView;
}
person Maulik Kundaliya    schedule 20.12.2013

Спасибо за @Richard Bown

Будет ли это лучшим ответом для Swift?

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
        if let titleLabel = view as? UILabel {
            titleLabel.text = "Your Text"
            return titleLabel
        } else {
            let titleLabel = UILabel()
            titleLabel.font = UIFont.boldSystemFontOfSize(16)//Font you want here
            titleLabel.textAlignment = NSTextAlignment.Center
            titleLabel.text = "Your Text"
            return titleLabel
        }
    }
person Scott Zhu    schedule 19.01.2016

Я думаю, вам нужно добавить NSFontAttributeName в свой список attributes, и вы могли бы использовать метод класса fontWithName:size: из UIFont

person zbMax    schedule 20.12.2013
comment
Пробовал, не работает: NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attribute:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName: [UIFont fontWithName:@HelveticaNeue-Light size:40]}]; - person user3121912; 20.12.2013
comment
У Вас есть какие-либо идеи? - person user3121912; 20.12.2013
comment
Извините, моя вина. NSFontAttributeName работает для диапазона текста. Поэтому вам нужно добавить что-то вроде [attString addAttribute:NSFontAttributeName value:/*your font*/ range:NSMakeRange(0, attString.length)]; - person zbMax; 20.12.2013
comment
замените attString.length на title.length и измените тип NSAttributedString на NSMutableAttributedString - person zbMax; 20.12.2013
comment
@zbMax Я могу подтвердить, что это не работает. Он игнорирует все случаи NSFontAttributeName. - person Bill Burgess; 30.04.2015

person    schedule
comment
Спасибо !! это было полезно. пожалуйста, используйте [tView setTextAlignment:NSTextAlignmentLeft] для выравнивания текста метки, поскольку UITextAlignmentLeft устарело, начиная с iOS 6.0. - person Sam; 30.08.2019