Show UIPickerView on label click

☆樱花仙子☆ 提交于 2019-12-11 04:26:31

问题


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 ?


回答1:


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
}



回答2:


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.



来源:https://stackoverflow.com/questions/42319153/show-uipickerview-on-label-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!