2016-12-02 77 views
2

我正在創建貨幣換算應用程序。貨幣應該選擇一個選擇器視圖,所有的數據已經在裏面。我的選擇器視圖字體目前是黑色的,但我想要它是白色的。我將如何改變字體的顏色(不是背景)?更改Picker View內的字體顏色

func numberOfComponents(in pickerView: UIPickerView) -> Int 
{ 
    return 1 
} 

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int 
{ 
    return pickerViewSource.count 
} 

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? 
{ 
    return pickerViewSource[row] 
} 

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int 

    price_kind = pickerViewSource[row] 
    switch price_kind { 
    case "USD": 
     label.text = "$ " + price_kind 
     rate = 1.0 
    case "EUR": 
     label.text = "€ " + price_kind 
     rate = 0.9461 
    case "GBP": 
     label.text = "£ " + price_kind 
     rate = 0.8017 
    case "RUB": 
     label.text = "₽ " + price_kind 
     rate = 64.3435 
    case "CNY": 
     label.text = "¥ " + price_kind 
     rate = 6.9137 
    case "YEN": 
     label.text = "¥ " + price_kind 
     rate = 6.26 
    case "AUD": 
     label.text = "$ " + price_kind 
     rate = 1.3498 
    case "CAD": 
     label.text = "$ " + price_kind 
     rate = 1.3483 
    default: 
     label.text = "$ " + price_kind 
     rate = 1.0 


    } 
+0

** picker.backgroundColor = UIColor.white **其中** picker **是您的UIPIcker對象的引用。 – Wolverine

回答

2

要更改文本的UIPickerView使用NSAttributedString內:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { 
    let str = pickerData[row] 
    return NSAttributedString(string: str, attributes: [NSForegroundColorAttributeName:UIColor.white]) 
} 
2

您可以使用attributedTitleForRow和NSAttributedString

請參考下面的代碼。

func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { 
    let attributedString = NSAttributedString(string: "some string", attributes: [NSForegroundColorAttributeName : UIColor.redColor()]) 
    return attributedString 
} 

如果你想用不同的顏色的每一行,然後使用下面的代碼。

func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { 
     var attributedString: NSAttributedString! 

     switch component { 
     case 0: 
      attributedString = NSAttributedString(string: "Zero", attributes: [NSForegroundColorAttributeName : UIColor.redColor()]) 
     case 1: 
      attributedString = NSAttributedString(string: "One", attributes: [NSForegroundColorAttributeName : UIColor.redColor()]) 
     case 2: 
      attributedString = NSAttributedString(string: "Two"), attributes: [NSForegroundColorAttributeName : UIColor.redColor()]) 
     default: 
      attributedString = nil 
     } 

     return attributedString 
    } 
+1

謝謝,它工作完美!這是我在這裏的第一個問題,我馬上得到了很好的答案,非常感謝你的幫助! – Jojo

+0

歡迎。當有人提出明確的代碼問題和可能的圖像,使其他人更容易回答。你做得很好。那麼你必須接受任何答案。 – Hasya

+0

但是如何改變Picker View中選定的特定索引處文本的顏色? –