2016-12-17 3 views
1

Попытка изменить шрифт в моем pickerView с помощью NSAttributedString:Настройка шрифта с помощью NSAttributedString

public func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { 
    guard let castDict = self.castDict else { 
     return nil 
    } 
    let name = [String](castDict.keys)[row] 
    switch component { 
    case 0: 
     return NSAttributedString(string: name, attributes: [NSForegroundColorAttributeName : AppColors.Rose.color, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)]) 
    case 1: 
     guard let character = castDict[name] else { 
      return NSAttributedString(string: "Not found character for \(name)", attributes: [NSForegroundColorAttributeName : AppColors.Rose.color, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)]) 
     } 
     return NSAttributedString(string: character, attributes: [NSForegroundColorAttributeName : AppColors.LightBlue.color, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)]) 
    default: 
     return nil 
    } 
} 

Цвет изменился, шрифт - не:

enter image description here

Что я делаю не так?

ответ

1

Короткий ответ будет заключаться в том, что вы ничего не делаете неправильно, это проблема со стороны Apple, поскольку они нигде не писали, что шрифты не могут быть изменены в UIPickerView.

Однако есть обходное решение.

С UIPickerViewDelegate вы должны ввести func pickerView(_ pickerView:, viewForRow row:, forComponent component:, reusing view:) -> UIView. Благодаря этому вы сможете предоставить пользовательский UIView для каждой строки.

Вот пример:

func pickerView(_ reusingpickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { 
    if let pickerLabel = view as? UILabel { 
     // The UILabel already exists and is setup, just set the text 
     pickerLabel.text = "Some text" 

     return pickerLabel 
    } else { 
     // The UILabel doesn't exist, we have to create it and do the setup for font and textAlignment 
     let pickerLabel = UILabel() 

     pickerLabel.font = UIFont.boldSystemFont(ofSize: 18) 
     pickerLabel.textAlignment = NSTextAlignment.center // By default the text is left aligned 

     pickerLabel.text = "Some text" 

     return pickerLabel 
    } 
} 
+0

Спасибо за подробный ответ. Да, сделал это с помощью пользовательского вида. Всегда старайтесь не использовать представления по соображениям производительности – zzheads

Смежные вопросы