Как изменить цвет текста UIPickerView?
Цвет UIPickerView по умолчанию для текста - черный. В Swift4 произошли некоторые обновления языка. Я нашел свое собственное решение и ответил ниже.
5 ответов
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let titleData = data[row]
let myTitle = NSAttributedString(string: titleData, attributes: [NSAttributedStringKey.foregroundColor: UIColor.yellow])
return myTitle
}
Вы можете использовать:
pickerView.setValue(UIColor.yellow, forKeyPath: "textColor")
Это изменит только цвет для текущей выбранной строки.
Смотрите также: /questions/5300930/xcode-uipickerview-izmenit-tsvet-fona-otdelnoj-stroki/5300945#5300945
Обновлено для Swift 5:
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
return NSAttributedString(string: parksPickerData[row], attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
}
У меня есть проект с PickerViews и DatePickers (внутри TableViewCell), и мне приходилось использовать разные предложения для каждого случая.
Для PickerViews:
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let titleData = "data"
let myTitle = NSAttributedString(string: titleData, attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
return myTitle
}
Для DatePicker:
datePicker.setValue(UIColor.lightGray, forKey: "textColor")