如何更改我的选择器的颜色?
我不想改变字体或文本。我的选择器已经填充并且按照我想要的方式工作,我想做的是将颜色从黑色更改为我的自定义白色。
如何更改我的选择器的颜色?
我不想改变字体或文本。我的选择器已经填充并且按照我想要的方式工作,我想做的是将颜色从黑色更改为我的自定义白色。
请查看:http://makeapppie.com/tag/uipickerview-in-swift/
如果你想要改变每个元素的标题颜色,你可以实现以下代码:
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let titleData = pickerData[row]
var myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 15.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()])
return myTitle
}
Swift 3:
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let titleData = pickerData[row]
let myTitle = NSAttributedString(string: titleData!, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 15.0)!,NSForegroundColorAttributeName:UIColor.white])
return myTitle
}
*适用于日期选择器和常规选择器
override func viewDidLoad() {
super.viewDidLoad()
pickerView.setValue(UIColor.blue, forKey: "textColor")
pickerView.setValue(UIColor.black, forKey: "backgroundColor")
}
Swift 4.0
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let titleData = arrayOfPickerData[row]
let myTitle = NSAttributedString(string: titleData, attributes: [.font:UIFont(name: "Georgia", size: 15.0)!, .foregroundColor:UIColor.white]))
return myTitle
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var label: UILabel
if let view = view as? UILabel { label = view }
else { label = UILabel() }
label.textColor = UIColor.blue
label.textAlignment = .center
label.font = UIFont(name: "My-Custom-Font", size: 20) // or UIFont.boldSystemFont(ofSize: 20)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.text = getTextForPicker(atRow: row) // implemented elsewhere
return label
}
使用Swift 4.0实现UIPickerView的多组件显示
每个"组件"都是您设计要在UIPickerView中显示的列表。例如,如果您有以下内容:一个包含名称的数组列表和另一个包含年龄的数组列表,并且这两个列表都以您选择某人的姓名和他们的年龄的方式显示。 第一个组件用于名字,在forComponent中为component == 0; 第二个组件用于年龄,在forComponent中为component == 1; 根据您列出的组件数量依此类推。
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
if component == 0 {
let nameData = namesArray[row]
let myNameData = NSAttributedString(string: nameData, attributes: [.foregroundColor:UIColor.white])
return myNameData
} else {
let ageData = ageArray[row]
let myAgeData = NSAttributedString(string: ageData, attributes: [.foregroundColor:UIColor.white])
return myAgeData
}
}