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
很高興我能幫忙:) –