如何更改UIPickerView文本颜色?

Ste*_*e B 5 uipickerview swift4

文本的默认UIPickerView颜色为黑色.Swift4中的语言有一些更新.我找到了自己的解决方案并在下面回答.

Ste*_*e B 22

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    return NSAttributedString(string: data[row], attributes: [NSAttributedStringKey.foregroundColor: UIColor.yellow])        
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*haw 9

你可以使用:

pickerView.setValue(UIColor.yellow, forKeyPath: "textColor")
Run Code Online (Sandbox Code Playgroud)

这只会更改当前选定行的颜色。

另见:https : //stackoverflow.com/a/9866686/5306470

  • 这只会在您为我移动选择器视图时更改颜色。 (11认同)

zou*_*tre 7

在故事板中,您可以添加textColor到关键路径:


Col*_*ill 5

为 Swift 5 更新:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    return NSAttributedString(string: parksPickerData[row], attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
}
Run Code Online (Sandbox Code Playgroud)