Kirill
Kirill

Reputation: 1472

Show UIPickerView on label click

I use UIPickerView to select data for label:

class BookingOptionsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var lblProfile: UILabel! 

    var data = ["1", "2", "3"]
    var picker = UIPickerView()

    override func viewDidLoad() {
        super.viewDidLoad()        
        picker.delegate = self
        picker.dataSource = self
        let tap = UITapGestureRecognizer(target: self, action: #selector(tap(gestureReconizer:)))
        lblProfile.addGestureRecognizer(tap)
        lblProfile.isUserInteractionEnabled = true
    }

    func tap(gestureReconizer: UITapGestureRecognizer) {
        print("*")
        picker.isHidden = false
    }

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

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

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        lblProfile.text = data[row]
        self.view.endEditing(true)
    }

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

When I click on label I want to show my UIPickerView, but picker.isHidden = false does not work. What should I do to display UIPickerView ?

Upvotes: 1

Views: 12848

Answers (2)

iRestMyCaseYourHonor
iRestMyCaseYourHonor

Reputation: 799

You can create a UILabel subclass and return canBecomeFirstResponder true. And then override the inputView to return the pickerView you want. Here is a topic that it is discussed UILabel doesn't show inputView.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318774

You never finish the setup of the picker view. You create it. You set its delegate and data source, but that's it. You need to set its frame. And you need to add it to the view controller's view (or some other appropriate parent view).

override func viewDidLoad() {
    super.viewDidLoad()        

    var pickerRect = picker.frame
    pickerRect.origin.x = // some desired value
    pickerRect.origin.y = // some desired value
    picker.frame = pickerRect
    picker.delegate = self
    picker.dataSource = self
    picker.isHidden = true
    view.addSubview(picker)

    let tap = UITapGestureRecognizer(target: self, action: #selector(tap(gestureReconizer:)))
    lblProfile.addGestureRecognizer(tap)
    lblProfile.isUserInteractionEnabled = true
}

Upvotes: 4

Related Questions