Search code examples
swiftcolorsuipickerviewselected

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?


Solution

  • 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