2015-03-24 248 views
5

如何更改我的選擇器顏色?更改UIPicker顏色

我不希望更改字體或文本。我的選擇器正在填充並按照我想要的方式工作,我想要做的是將顏色從黑色更改爲我自定義的白色。

+0

變化是什麼顏色:字體,背景,所選擇的項目中,未被選中的項目? – 2015-03-24 21:54:20

回答

17

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

這正是我所需要的,並使我能夠在黑色背景上的選取器視圖中使用白色文本。謝謝 – 2016-01-20 21:14:50

+0

@Youri Nooijen,非常適合我,謝謝。 – 2016-12-23 06:28:08

2

如果您想要更多控制自定義拾取器中的每個元素...

使用UIPickerViewDelegate'sviewForRow」方法。

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更復雜。

0

雨燕4.0

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { 
    let titleData = arrayOfPickerData[row] 
    let myTitle = NSAttributedString(string: titleData, attributes: [NSAttributedStringKey.font:UIFont(name: "Georgia", size: 15.0)!,NSAttributedStringKey.foregroundColor:UIColor.white]) 
    return myTitle 
}