ios - 在 UIPickerView 中更改选定行的颜色,滚动时也是如此

标签 ios swift uikit uipickerview

我必须更改 UIPickerView 中选定行的颜色。

我确实设法改变了颜色,我知道这个问题已经有好几个回复了,无论如何那些都不让我满意:通过这些实现,pickerview 的动画是有问题的,我不喜欢它。

这是当前解决方案的代码

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    var label: UILabel
    if view == nil {
      label = UILabel()
    } else if view is UILabel {
      label = view as! UILabel
    } else {
      label = UILabel()
    }

    let title: NSAttributedString
    if self.model?.selectedValue == row {
      title = UIPickerView.attributedString(with: .selectedRow, text: "\(model?.years[row] ?? 0)")
    } else {
      title = UIPickerView.attributedString(with: .unselectedRow, text: "\(model?.years[row] ?? 0)")
    }

    label.attributedText = title
    return label
}

当用户滚动时,我会重新加载组件。

但正如您在下图中看到的那样,当用户滚动时,绿色字段会移动,并且有几分之一秒的时间绿色标签位于选择器指示符下方并且所选行为黑色。

pickerview while scrolling after scroll but before the reload

我想要的是,选择器指示器内的所有内容都是绿色,而外部保持默认的灰色阴影。

我该如何实现?

最佳答案

您应该为此使用 attributedTitleForRow,无需使用 NSAttributedString 创建您自己的标签。在您的 didSelectRow 中,您重新加载所有组件,以便能够重置所有颜色并将新选择的颜色设置为绿色。

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let color = (row == pickerView.selectedRow(inComponent: component)) ? UIColor.green : UIColor.black
    return NSAttributedString(string: self.model[row], attributes: [NSForegroundColorAttributeName: color])
}

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

关于ios - 在 UIPickerView 中更改选定行的颜色,滚动时也是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47048600/

相关文章:

iphone - 为 iPad 设置图标,应用程序的目标设备是 iPhone

arrays - 在 Swift 5.1 中,在不知道键的情况下,根据 Date 类型的字典值对字典数组进行排序?

ios - 如何在 iOS 8 中判断目标界面的方向?

swift - 如何删除最后一个实例化的ViewController并使最后一个TableViewController变为事件状态

ios - UIView 中的 Swift UILabel

ios - UIImageView 驻留在视网膜 4"

objective-c - UIKit 中是否有内置事件处理的基/实用程序类?

ios - 识别后使UIGestureRecognizer失败的方法?

objective-c - 如何将宏和常量放入 iOS 项目的 .pch 文件中?

ios - 更新布局 anchor 未按预期工作