Seong Min Choo
Seong Min Choo

Reputation: 147

How to change UIPickerView title text color based on position

I want to set an UIPickerView so that the title of the row that is selected (in the center) is blue, and the two rows above and below have text color black, and the others color gray..

so it will look something like this

enter image description here

is there any way to do this in swift?

Upvotes: 0

Views: 1985

Answers (2)

Aalaa
Aalaa

Reputation: 57

@Deryck Lucian update answer:

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let pickerLabel = UILabel()
        pickerLabel.textColor = (row == pickerView.selectedRow(inComponent: component)) ? UIColor.red : UIColor.green
        pickerLabel.text = List[row]
        pickerLabel.textAlignment = .center
        return pickerLabel
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        pickerView.reloadComponent(component)

    }

Upvotes: 1

Deryck Lucian
Deryck Lucian

Reputation: 475

Yes, it is. Below example is for one component.

var pickerArray = [String]()
var selectedRow: Int {
    return pickerView.selectedRow(inComponent: 0)
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    pickerView.reloadComponent(component)
}

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    var color = UIColor.gray

    if row == selectedRow {
        color = UIColor.blue
    } else if selectedRow == row - 1 || selectedRow == row + 1 {
        color = UIColor.black
    }

    return NSAttributedString(string: pickerArray[row], attributes: [NSAttributedString.Key.foregroundColor: color])
}

Maybe it exists another way, but I think this will be sufficient :]

// Update1: NOT RECOMMENDED

You could override (hitTest:point:event) and return self from it and then reload the components on (touchesMoved:touches:event). BUT the scroll and touches on the picker will not work. You will need to do something else :(

// Update2: The result: enter image description here

Upvotes: 3

Related Questions