Font color in the columns of a UIPickerView

1

I do not know how to change the color of the elements within a UIPickerView .

As you can see in the capture, the only thing I need is for all the texts to be blue, according to the rest of the application.

Now the texts and numbers come out in black that the default color of the picker.

    
asked by Shadros 09.03.2016 в 16:04
source

1 answer

2

It's very simple, you just have to implement one of its delegated methods to return a NSAttributedString . For example, the complete implementation of your case would be something like this:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {

    return 2

}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    return component == 0 ? 31 : 4

}

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

    let textColor = UIColor.blueColor()

    if component == 0 {

        return NSAttributedString(string: "\(row)", attributes: [NSForegroundColorAttributeName : textColor])

    } else {

        switch row {
        case 0:
            return NSAttributedString(string: "días", attributes: [NSForegroundColorAttributeName : textColor])
        case 1:
            return NSAttributedString(string: "semanas", attributes: [NSForegroundColorAttributeName : textColor])
        case 2:
            return NSAttributedString(string: "meses", attributes: [NSForegroundColorAttributeName : textColor])
        case 3:
            return NSAttributedString(string: "años", attributes: [NSForegroundColorAttributeName : textColor])
        default:
            return nil
        }

    }

}
    
answered by 09.03.2016 / 16:29
source