2016-12-02 105 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中选定的特定索引处文本的颜色? –