在 UIPickerView 中更改 selectedRow 的颜色,也在滚动时 [英] Change color of selectedRow in UIPickerView, also when rolling

查看:51
本文介绍了在 UIPickerView 中更改 selectedRow 的颜色,也在滚动时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在 UIPickerView 中更改所选行的颜色.

I have to change the color of the selected row in a UIPickerView.

我确实设法改变了颜色,我知道这个问题已经有好几个回复了,反正这些都不满足我:通过这些实现,pickerview 的动画有问题,我不喜欢它.

I did managed to change the color, i know that the question already have several replies, anyway those do not satisfy me: with those implementation, the animation of the pickerview is glitchy and i don't like it.

这是当前解决方案的代码

This is the code of the current solution

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
}

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

And when the user scrolls, I reload the components.

但正如您在下图中所见,当用户滚动时,绿色字段会移动,并且在几秒钟内绿色标签位于选择器指示器下方,所选行为黑色.

But as you can see in the images below, when a user scroll, the green field moves and there is a fraction of seconds in which the green label is below the selector indicator and the selected row is black.

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

What I'd like to have is that everything inside the selector indicator is green while what outside keeps the default shades of grey.

我该如何实施?

推荐答案

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

You should use attributedTitleForRow for this instead, no need to create your own label with an NSAttributedString. In your didSelectRow your reload all your components to be able to reset all colors and set the new selected one to green.

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

这篇关于在 UIPickerView 中更改 selectedRow 的颜色,也在滚动时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆