[英]Change the font color inside a 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
}
要更改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])
}
您可以使用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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.