Search code examples
iosarraysswiftcomboboxuipickerview

Treat an UIPickerView like a combo/select box


I'm working with XCode 8.2.1, Swift 3 and iOS10.

I've a list of items with the following format:

ID | Name
---------
1 | John
2 | Maria
3 | Peter
4 | Roger

The code looks like this:

var formsList = [1:"John", 2:"Maria", 3:"Peter", 4:"Roger"]

What I want to do is to set that data into an UIPickerView, so when someone chooses for example John, the ID 1 is returned, or if someone chooses Peter, the ID 3 is returned.

I do other stuff once I get that ID, that's why I need it.

Any idea or suggestion on how I can achieve this?

Thanks!


Solution

  • You just need to sort your dictionary by its keys and use it as your picker data source:

    let formsList = [1:"John", 2:"Maria", 3:"Peter", 4:"Roger"]
    let dataSource = formsList.sorted{$0.key<$1.key}
    

    This way you have all your dictionary names sorted in an array including their IDs. Your picker should look something like this:

    class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
        @IBOutlet weak var pickerView: UIPickerView!
        @IBOutlet weak var label: UILabel!
        let formsList = [1:"John", 2:"Maria", 3:"Peter", 4:"Roger"]
        var dataSource: [(key: Int, value: String)] = []
        override func viewDidLoad() {
            super.viewDidLoad()
            dataSource = formsList.sorted{$0.key<$1.key}
            pickerView.delegate = self
            pickerView.dataSource = self
            label.text = "id: " + String(dataSource[pickerView.selectedRow(inComponent: 0)].key) + " - " + "name: " + dataSource[pickerView.selectedRow(inComponent: 0)].value
        }
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }
        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return dataSource.count
        }
        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return dataSource[row].value
        }
        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            label.text = "id: " + String(dataSource[row].key) + " - " + "name: " + dataSource[row].value
        }
    }
    

    sample