Search code examples
iosswiftuipickerview

Multiple Custom UIPickerViews in the same UIView in swift


Im trying to have two different pickerViews on the same viewController and let them represent different data. I have tried a different ways to do this, but both picker views showing same Data, but can't put it all together. Any help would be awesome!

here is my code:

 @IBOutlet weak var Eventtype: UITextField!


    let pickerView = UIPickerView()

    var Eventstype = ["Birthday" , "Marriege" , "Get together", "Conference"]

    @IBOutlet weak var datepickertxt: UITextField!

    var datepicker = UIDatePicker()

    @IBOutlet weak var Duration: UITextField!
     let duration = UIPickerView()

    var Durations = ["6-8","1-5","7-9","10-12"]


    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
        pickerView.delegate = self
        pickerView.dataSource = self
        duration.delegate = self
        duration.dataSource = self
        Eventtype.inputView = pickerView
        Duration.inputView = duration
        // Do any additional setup after loading the view.
    }
    ////For Event Picker view

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

        return 1


    }

     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if (pickerView.tag == 0) {
            //pickerView1
            return Eventstype.count
        } else if (duration.tag == 1){
            //pickerView2
            return Durations.count
        }
        return 1
        //return DurationTxt.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView.tag == 0) {

            return Eventstype[row]
        } else if (duration.tag == 1){

           return Durations[row]
        }

        return ""
    }
        //return DurationTxt[row]


    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView.tag == 0) {
            Eventtype.text = Eventstype[row]
            self.view.endEditing(false)
        }else if (duration.tag == 1){
            Duration.text = Durations[row]
            self.view.endEditing(true)

        }

    }

Solution

  • Set the tags for pickerview in viewDidLoad as shown below,

    pickerView.tag = 0
    duration.tag = 1