如何更改UIPickerView和UIDatePicker的字体颜色?

6
我有一个包含UIPickerViewUIDatePickerviewController,如下面从我的storyboard截图所示。 The screenshot from my storyboard 我尝试按照这里所述添加运行时属性。但是,遵循此方法只更改了最初突出显示的文本的字体颜色。 我想将我的pickerView和datePicker中的文本颜色更改为白色。我不知道如何实现这一点。
4个回答

14

你需要编写这行代码来更改日期选择器文本颜色。

 self.datePicker.setValue(UIColor.white, forKeyPath: "textColor")

它将改变UIDatePicker的文本颜色。

对于PickeView,您需要设置属性字符串,例如:

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

    return NSAttributedString(string: "Your Text", attributes: [NSForegroundColorAttributeName:UIColor.blue])
}

2
非常感谢。很遗憾苹果不会为此提供一个简单的setTextColor方法。我无法相信他们认为只有黑色字体是可以接受的。 - Supertecnoboff

2
这两行代码救了我的一天。
    NepaliDatePicker.setValue(UIColor.white, forKey: "textColor")
    EnglishDatePicker.setValue(UIColor.white, forKey: "textColor")

1
您可以使用“viewForRow”委托方法来处理“UIPickerView”。
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
     // Your custom view with custom font here
}

对于UIDatePicker,您无法更改字体,但可以使用此代码更改文本颜色。
datePicker.setValue(UIColor.whiteColor(), forKeyPath: "textColor")
datePicker.datePickerMode = .CountDownTimer
datePicker.datePickerMode = .DateAndTime

希望这有所帮助。

-1

这是我在问题中引用的同一个问题。 - amagain
好的。你得到了答案吗?@amagain - jegadeesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接