我必须更改 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
}
当用户滚动时,我会重新加载组件。
但正如您在下图中看到的那样,当用户滚动时,绿色字段会移动,并且有几分之一秒的时间绿色标签位于选择器指示符下方并且所选行为黑色。
我想要的是,选择器指示器内的所有内容都是绿色,而外部保持默认的灰色阴影。
我该如何实现?
最佳答案
您应该为此使用 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/