【问题标题】:How to change UIPickerView title text color based on position如何根据位置更改 UIPickerView 标题文本颜色
【发布时间】:2018-11-20 06:05:15
【问题描述】:

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

所以它看起来像这样

有什么方法可以快速做到这一点吗?

【问题讨论】:

    标签: swift colors uipickerview selected


    【解决方案1】:

    是的,是的。下面的示例是针对一个组件的。

    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) 并从中返回 self,然后在 (touchesMoved:touches:event) 上重新加载组件。但是选择器上的滚动和触摸将不起作用。您将需要做其他事情:(

    // 更新2:结果:

    【讨论】:

    • 我一直在寻找的是在滚动时改变颜色,但我想这对于我们使用 UIPickerView 提供的 APi 是不可能的。但感谢您的回复!
    • 查看我的更新。也许你会比我让它工作的运气更好:]
    • 顺便说一句,我的 NSattributedString 的字体部分不工作你知道为什么吗?
    • 嗯,奇怪。我添加了结果的截图
    • 你用的是:func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerArray[row] }
    【解决方案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)
    
        }
    

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多