2015-03-24 21 views
5

Làm cách nào để thay đổi màu của bộ chọn của tôi?Thay đổi màu UIPicker

Tôi không muốn thay đổi phông chữ hoặc văn bản. Bộ chọn của tôi là phổ biến và hoạt động chính xác theo cách tôi muốn, điều tôi muốn làm là thay đổi màu từ màu đen sang màu trắng tùy chỉnh của tôi.

+0

Thay đổi màu sắc của những gì: font, nền, mục đã chọn, các mục không được chọn? –

Trả lời

17

Hãy xem tại địa chỉ: http://makeapppie.com/tag/uipickerview-in-swift/

Nếu bạn muốn thay đổi màu sắc tiêu đề của bạn của mỗi yếu tố bạn có thể thực hiện:

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

Điều này đã làm chính xác những gì tôi cần và cho phép tôi sử dụng văn bản màu trắng trong chế độ xem bộ chọn trên nền đen. Cảm ơn bạn –

+0

@Youri Nooijen, tuyệt vời cho tôi, Cảm ơn. –

2

Nếu bạn muốn kiểm soát nhiều hơn tùy chỉnh từng phần tử trong bộ chọn ...

Sử dụng phương thức 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 
} 

Rõ ràng chế độ xem bạn đang quay trở nên phức tạp hơn chỉ là một nhãn UILabel.

0

Swift 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 
}