I’m loading data from my API that contains a Name (name) and an ID (id) + some other info. How could I load the names into a UIPickerView, and get the id for the selected one?
Hi Braden,
Welcome to the community!
Below is the code I use to display a picker of colors for a user to select the background of the app.
If you call the delegate and datasource, Xcode will stub out the required methods, just like in a tableView.
Utilize the didSelectRow method to grab the id which I assume to have listed in a struct somewhere.
This should get you going.
Blessings,
—Mark
extension BackgroundColorVC: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
textColor.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return textColor[row]
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return 200
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let pickerLabel = UILabel()
let titleData = textColor[row]
let myTitle = NSAttributedString(string: titleData, attributes: [NSAttributedString.Key.font:UIFont(name: "Georgia", size: 26.0)!, NSAttributedString.Key.foregroundColor:UIColor.darkGray])
pickerLabel.attributedText = myTitle
//Add color
pickerLabel.backgroundColor = colors[row]
pickerLabel.textAlignment = .center
return pickerLabel
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat
{
return 60
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
backgroundColor = textColor[row]
}
}