1
我有一个创建了pickerview用下面的代码更改所选行标签颜色选择器视图SWIFT 1.2
@IBOutlet var myPicker: UIPickerView!
var colors: [String] = ["red","green","blue"]
override func viewDidLoad() {
super.viewDidLoad()
myPicker = UIPickerView()
myPicker.dataSource = self
myPicker.delegate = self
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return colors.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return colors[row] as! String
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
现在我想,如果我更改所选行的标签(文字)的颜色,例如向下滚动并选择蓝色,文本颜色应该变成橙色,其他2个标签将变成黑色,当我选择其他行时,它们也会变成黑色。我曾尝试下面的代码,但它不工作
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
var pickerLabel = UILabel()
var myTitle:NSAttributedString
let titleData = colors[row]
if pickerView.selectedRowInComponent(component) == row {
myTitle = NSAttributedString(string: titleData, attributes: [NSForegroundColorAttributeName: UIColor.redColor()])
} else {
myTitle = NSAttributedString(string: titleData, attributes: [NSForegroundColorAttributeName: UIColor.blueColor()])
}
//This way you can set text for your label.
pickerLabel.attributedText = myTitle
return pickerLabel
}
我不知道我是否应该与didSelectRow或viewForRow方法实现它,有人可以请帮我在这?
你是真棒!奇迹般有效!非常感谢@AndréSlotta :) – sam
很高兴我能帮忙:) –