How to update label with uipickerview value

 

This tutorial is updated for x code 7.3 & swift 2.2

If you have limited number of possible input then uipickerview can save you a lot of time. Otherwise you will have to set condition after condition for what kinds of inputs are allowed.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set the values as follows and save it on your desktop.

new x code project

 

2. Go to main storyboard and select view controller. Set its size to iPhone 4”

size iPhone 4 inch

 

3. Add label and picker in the storyboard.

label & picker view

 

4. Connect label as outlet to swift file

label to swift file

 

5. Connect uipickerview as outlet to swift file

picker as outlet

 

6. Connect datasource & delegate of picker view to view controller

Screen Shot 2015-03-13 at 4.49.23 pm

7. Add UIPickerViewDatasource & UIPickerViewDelegate to class view controller

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

8. Create array of strings to show in picker view

let color = ["Red", "Green", "Yellow", "Blue"]

9. Set number of columns in picker view

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

10. Set number of items in column & now the error will go away

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

11. Now you have to connect array to picker view so it can show all strings

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    return color[row]
}

12. When you select one string from picker view then you need to update label

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    textLabel.text = color[row]
}

Now build and run app in iPhone 5s

iOS Simulator Screen Shot 13-Mar-2015 5.10.39 pm
Download X code file
Challenge: show two columns in uipickerview & update label from strings of each column

iOS Simulator Screen Shot 13-Mar-2015 5.16.04 pm
Download X code file

Total 6 Votes
5

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?