gpt4 book ai didi

ios - 在选择器 View swift 1.2 中更改选定的行标签颜色

转载 作者:搜寻专家 更新时间:2023-11-01 06:07:26 24 4
gpt4 key购买 nike

我使用以下代码创建了 pickerview

    @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 方法来实现它,有人可以帮我解决这个问题吗?

最佳答案

您可以执行以下操作:

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

var colors = ["red","green","blue"]

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return colors.count
}

func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let color = (row == pickerView.selectedRowInComponent(component)) ? UIColor.orangeColor() : UIColor.blackColor()
return NSAttributedString(string: colors[row], attributes: [NSForegroundColorAttributeName: color])
}

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

关于ios - 在选择器 View swift 1.2 中更改选定的行标签颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33719136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com