2016-12-17 64 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

相關問題