-2

I have a view with UITapGestureRecognizer

I want to show uidatepicker, when I tap on view

How can I do it ?

thanks in advance

amir.nh
  • 91
  • 7

2 Answers2

1

I'm not sure exactly what you want, but if you just have something like this?

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var datePicker: UIDatePicker!

    @IBAction func viewTapped(sender: Any) { // link gesture recogniser here
        datePicker.isHidden = false
    }

    override func viewDidLoad() {
        datePicker.isHidden = true // or set hidden checkbox to true in the picker's attributes inspector
    }
}
0

Just declare your picker datasource inside the touch action.

// in viewDidload method
let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.touchAction (_:)))
self.view.addGestureRecognizer(gesture) // could be your custom view also

//  for Swift 3
func touchAction(_ sender:UITapGestureRecognizer){  
    // datasource
    self.pickerData = ["data1","data2" .. ect]

    if pickerData != nil{
        self.picker.delegate = self
        self.picker.dataSource = self
    } 
}

Note: your controller class should confirm UIPickerViewDelegate, UIPickerViewDataSource in order to use picker delegates.

vaibhav
  • 4,038
  • 1
  • 21
  • 51
  • are you seen this your selector name is different `#selector (self.touchAction (_:)` and action name is different `func someAction(_ sender:UITapGestureRecognizer){` – Anbu.Karthik Aug 24 '17 at 05:06
  • @Anbu.Karthik, please see the updated. – vaibhav Aug 24 '17 at 05:09
  • one more thing , you can assign the datasource and delegate in viewdidload also inside the gesture only you can refresh the picker – Anbu.Karthik Aug 24 '17 at 05:11
  • @Anbu.Karthik, see updated ans, this prevents the unexpected crash when the data source of picker is nil, if we confirm the delegates in `viewdidload` then the data source cant be nil and delegates called everytime. – vaibhav Aug 24 '17 at 05:22