更改UIPicker颜色

时间:2015-03-24 21:50:15

标签: ios swift colors uipickerview

如何更改选择器的颜色?

我不想更改字体或文字。我的选择器填充并且完全符合我的要求,我想要做的是将颜色从黑色更改为我的自定义白色。

5 个答案:

答案 0 :(得分:18)

看看: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
}

斯威夫特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
}

答案 1 :(得分:4)

Swift 4.0

Dim list = New List(Of Tuple(Of String, Integer()))

list.Add(Tuple.Create("Name1", {1,2,3}))
list.Add(Tuple.Create("Name1", {1,2,3}))

For Each pair In list
    Debug.Print(pair.Item1 & ": " & String.Join(",", pair.Item2))
Next

答案 2 :(得分:3)

如果您想要 更多控制 自定义选择器中的每个元素......

使用UIPickerViewDelegate's viewForRow ”方法。

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
}

显然,您返回的视图可能比UILabel更复杂。

答案 3 :(得分:0)

在UIPickerView中具有多个组件的Swift 4.0

每个“组件”都是您设计的UIPickerView中显示的列表。例如,如果您具有以下内容:数组中的姓名列表和数组中的年龄列表,并且两者都显示出来,以便您选择人员姓名及其年龄。   forComponent中的第一个组件“名称”是component == 0;   forComponent中的第二个组件“年龄”为componennt == 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
    }

}

答案 4 :(得分:0)

*对于日期选择器和普通选择器

   override func viewDidLoad() {
   super.viewDidLoad()
   pickerView.setValue(UIColor.blue, forKey: "textColor")
   pickerView.setValue(UIColor.black, forKey: "backgroundColor")
 }