我使用UIPickerView
为标签选择数据:
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]
}
}
当我点击标签时,我想显示我的UIPickerView
,但 picker.isHidden = false
不起作用。
我该怎么做才能显示UIPickerView
?
答案 0 :(得分:4)
您永远不会完成选择器视图的设置。你创造它。您设置了它的委托和数据源,但就是这样。你需要设置它的框架。您需要将其添加到视图控制器的视图(或其他一些适当的父视图)。
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
}
答案 1 :(得分:0)
您可以创建UILabel子类并返回canBecomeFirstResponder true。然后重写inputView以返回所需的pickerView。这是UILabel doesn't show inputView讨论的主题。