2016-12-17 106 views
1

使用NSAttributedString我pickerView尝试改变字体:设置字体使用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

简短的回答是你没有做错什么,这是苹果公司的一个问题,因为他们没有在UIPickerView中的任何地方写字体。

但是,有一种解决方法。您需要执行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