Sylar
Sylar

Reputation: 12072

Show UIPickerView on Gesture Tapped

My current app works when I tapped a text field, it would bring up the UIPickerView, but what if I tapped an image itself (gesture is placed over the image)?

class SomeVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
  @IBOutlet weak var inputLabel: UITextField!
  @IBOutlet weak var laImageGestureTapped: UITapGestureRecognizer!

  let demoPicker = UIPickerView()

  // viewDidLoad()
  inputLabel.inputView = demoPicker // All is well with this.

  // How to open the UIPickerView with laImageGestureTapped?

  // I have omitted the required functions for: numberOfRowsInComponent, viewForRow, didSelectRow, numberOfComponents etc
}

Am I searching with the correct words?

All I want is to show the picker when the image is tapped. Im not worried about didSelectRow as there will be an hidden label to do x, y and z.

If this question was already asked and answered, please to direct me. Thanks.

Upvotes: 1

Views: 3887

Answers (1)

Benjamin Lowry
Benjamin Lowry

Reputation: 3789

Here is an alternative method to putting a clear textfield over your image:

  1. Create a button that has your image assigned to its background image property
  2. Initialize your pickerView with its frame off of the screen
  3. Create a IBAction for your button that calls the pickerView onto the screen and creates a tap gesture and adds that your view
  4. Create the method that the tap gesture will call when fired, which will send your pickerView back off of the screen

Here is the relevant code:

class VC: UIViewController {
    var pickerView = UIPickerView()

    override func viewDidLoad() {
        super.viewDidLoad()
    ...
        pickerView = UIPickerView(frame: CGRect(x: 0, y: self.view.bounds.height, width: self.view.bounds.width, height: 100)) //Step 2

    }

    @IBAction func buttonPressed(sender: UIButton){ //Step 3

        UIView.animate(withDuration: 0.3, animations: {
            self.pickerView.frame = CGRect(x: 0, y: self.view.bounds.size.height - self.pickerView.bounds.size.height, width: self.pickerView.bounds.size.width, height: self.pickerView.bounds.size.height)
    })
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doneWithPickerView))
        view.addGestureRecognizer(tapGesture)

    }

    func doneWithPickerView() { //Step 4

        UIView.animate(withDuration: 0.3, animations: {
            self.pickerView.frame = CGRect(x: 0, y: self.view.bounds.size.height, width: self.pickerView.bounds.size.width, height: self.pickerView.bounds.size.height)
        })
    }
}

I think it's better practice in general to not use invisible views as they can caused trouble for your later on. Hope this helps.

Upvotes: 2

Related Questions