How do I change the text color of UIPickerView with multiple components in Swift?
Asked Answered
S

5

20

Below code will change the font colour of the picker view of all 3 components. However, it crash when I try to spin the wheel. I think it has to do with the didSelectRow function. Maybe the two function have to be nested somehow? Any idea?

    func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    var attributedString: NSAttributedString!
    if component == 0 {
        attributedString = NSAttributedString(string: a.text!, attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
    }
    if component == 1 {
        attributedString = NSAttributedString(string: b.text!, attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
    }
    if component == 2 {
        attributedString = NSAttributedString(string: c.text!, attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
    }
    return attributedString
}


func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){

    switch component {
    case 0:
        aOutput.text = a[row]      -->  **Code breaks**
    case 1:
        bOutput.text = b[row]
    case 2:
        cOutput.text = c[row]
    default:
        10
    }
Slander answered 17/9, 2014 at 21:27 Comment(3)
Have you tried anything? You should try and make some effort before asking.Faithfaithful
Yes of course, spent hours and hours, enrolled in 2 courses - been working on this app for a week non-stop from scratch with no programming background. But it is hard, all the tutorials are in playground. SO while I get the logic right, I have trouble understanding what code goes where. All the initialising (I think it is called) and scope of swift/object C.Slander
and the Scope. It doesn't help to know how to write a switch/case statement in Playground if you don't understand what statement like "var mySpeechSynthesizer: AVSpeechsynthesizer..." is, where it goes and the order of how you call them and what to call them. I don't even know the name of what I don't know...lol How do you figure out stuff like that without asking, tell me because I can't find it in the e-book or in course or on YoutubeSlander
M
35

The following pickerView:attributedTitleForRow:forComponent: method implementation should help you:

func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let attributedString = NSAttributedString(string: "some string", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
    return attributedString
}

Update

If you want to use attributedString in multiple if or switch statements, the following UIViewController subClass example will help you:

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var picker: UIPickerView!

    let arrayOne = ["One", "Two", "Three", "Four", "Five", "Six"]
    let arrayTwo = ["Un", "Deux", "Trois", "Quatre", "Cinq", "Six"]
    let arrayThree = [1, 2, 3, 4, 5, 6]


    override func viewDidLoad() {
        super.viewDidLoad()

        picker.delegate = self
        picker.dataSource = self
    }

    func numberOfComponentsInPickerView(_: UIPickerView) -> Int {
        return 3
    }

    func pickerView(_: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch component {
        case 0:
            return arrayOne.count
        case 1:
            return arrayTwo.count
        case 2:
            return arrayThree.count
        default:
            return NSNotFound
        }
    }

    func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        var attributedString: NSAttributedString!

        switch component {
        case 0:
            attributedString = NSAttributedString(string: arrayOne[row], attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
        case 1:
            attributedString = NSAttributedString(string: arrayTwo[row], attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
        case 2:
            attributedString = NSAttributedString(string: toString(arrayThree[row]), attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
        default:
            attributedString = nil
        }

        return attributedString
    }

    func pickerView(_: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        switch component {
        case 0:
            println(arrayOne[row])
        case 1:
            println(arrayTwo[row])
        case 2:
            println(arrayThree[row])
        default:
            break
        }
    }

}
Misfortune answered 17/9, 2014 at 22:25 Comment(8)
Hi, thank you so much, that changed the color! However it also changed the array - the text in the picker view. I guess I am meant to replace it with the name of the array? There is another complicating factor, i have 3 components (i.e. 3 columns.Slander
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{ return 3 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ switch component { case 0: return a.count case 1: return b.count case 2: return c.count default: return 10 } }Slander
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{ switch component { case 0: return a[row] case 1: return b[row] case 2: return c[row] default: return "oops" } }Slander
Thank you for your response ! Line: let attributedString: NSAttributedString! --> error/yellow: Immutable value is default initialised and can never be changed. Line(s) attributedString = NSAttributedstring.... --> error/red: Cannot assign to 'let' value 'attributedString'Slander
Wow, that almost worked! Now the picker view has changed color and the components are "initialised with the first value in the array. However, when I flick the wheel it stays at the first value in the array. Xcode also shows a green breakpoint on the first iteration of the func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){. I think your code must somehow be "nested" inside the other code or visa versa so that the wheel are filled with all the value in a.text, b.text and c.text. I will update question.Slander
I've edited my answer with a UIViewController subClass containing a UIPickerView (IBOutlet) with 3 components and text in red. It worked fine with a Xcode Single View Application template.Misfortune
I had some real issues in other parts of the code with casting variables between string and Int. And I noticed something in your code which I rewrote to --> NSString(string: toString(arrayOne[0])) and --> return NSString(string: toString(arrayOne[row])). Both solved to other issues I had. But while I have a gut feeling about what they do, and it is why I tried it, I am not quite sure what it does, it just solved a lot of errors. Can you explain please?Slander
Yes of course, but I can't, yet, I need 15 in reputation before I can vote... I will though ! ThanksSlander
P
18

Swift 4.0

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    return NSAttributedString(string: pickerData[row], attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
}
Pumpernickel answered 16/1, 2018 at 11:49 Comment(0)
V
8

Swift 3

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        let attributedString = NSAttributedString(string: "YOUR STRING", attributes: [NSForegroundColorAttributeName : UIColor.white])
        return attributedString
    }
Vehicle answered 10/2, 2017 at 1:36 Comment(0)
P
2

Swift 5

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    return NSAttributedString(string: pickerData[row], attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
}
Polacre answered 25/8, 2021 at 14:3 Comment(0)
S
1

enter image description hereThis code snippet works for me

extension UIPickerView {
@IBInspectable var pickerTextColor:UIColor? {
    get {
        return self.pickerTextColor
    }
    set {
        self.setValue(newValue, forKeyPath: "textColor")
    }
}}
Slavic answered 3/2, 2021 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.