如何根据位置更改 UIPickerView 标题文本颜色

How to change UIPickerView title text color based on position

我想设置一个UIPickerView,让选中的行标题(中间)为蓝色,上下两行的文本颜色为黑色,其他行的文本颜色为灰色..

所以它看起来像这样

在 swift 中有什么方法可以做到这一点吗?

是的,是的。下面的例子是一个组件。

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])
}

也许它存在另一种方式,但我认为这就足够了:]

// 更新 1:不推荐

您可以从中覆盖 (hitTest:point:event) 和 return self,然后在 (touchesMoved:touches:event) 上重新加载组件。但是选择器上的滚动和触摸将不起作用。您将需要做其他事情:(

//更新2:结果:

@Deryck Lucian 更新答案:

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)

    }