vkoh
vkoh

Reputation: 11

Picker View - Textfield not updating

I am trying to make a drop down list and is experimenting with using the PickerView. But i could not find a way to update the textfield after selecting the items in the Picker View.

I suspect the “didSelectRow” of the pickerView function wasn’t called at all though I don’t know how to check it. (I tried to print the selected row but nothing happens).

This is what I did at the Interface Builder :

make a textfield. drag the Picker View from Library to the interface.

connect the outlets and PickerView.

ctl drag the PickerView to the yellow icon at View Controller and select delegate and datasource.

ctl drat the textfield to the yellow icon at the View Controller and select delegate.

hope someone can kindly help.

following are my codes :

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var pickerBox: UIPickerView!
@IBOutlet weak var textBox: UITextField!

var list = ["Item 1", "Item 2", "Item 3"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    }

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

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

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
     var listingTypesArray = Array(list)
     return listingTypesArray[row]
        }

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, forComponent component: Int) {
    self.textBox.text = list[row]
    print("Row: \(row)")
    }

}

Upvotes: 1

Views: 130

Answers (1)

You forgot to add delegate and datasource

    override func viewDidLoad()
     {
        super.viewDidLoad()
     // Do any additional setup after loading the view.
        self. pickerBox.delegate = self
        self. pickerBox.dataSource = self

     }

Upvotes: 0

Related Questions