var toolBar = UIToolbar()
var picker = UIPickerView()
在您的按钮操作中添加以下代码。我已经在工具栏中添加了一个Done
按钮来关闭选择器。
注意:如果您不想这样做,只需在viewDidLoad
中编写所有代码,并在您的按钮操作中仅编写以下代码:self.view.addSubview(picker)
和self.view.addSubview(toolBar)
@IBAction func YOUR_BUTTON__TAP_ACTION(_ sender: UIButton) {
picker = UIPickerView.init()
picker.delegate = self
picker.dataSource = self
picker.backgroundColor = UIColor.white
picker.setValue(UIColor.black, forKey: "textColor")
picker.autoresizingMask = .flexibleWidth
picker.contentMode = .center
picker.frame = CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 300)
self.view.addSubview(picker)
toolBar = UIToolbar.init(frame: CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 50))
toolBar.barStyle = .blackTranslucent
toolBar.items = [UIBarButtonItem.init(title: "Done", style: .done, target: self, action: #selector(onDoneButtonTapped))]
self.view.addSubview(toolBar)
}
您可以通过点击“完成”按钮来删除工具栏以及选择器视图。
@objc func onDoneButtonTapped() {
toolBar.removeFromSuperview()
picker.removeFromSuperview()
}
UIPickerView
的委托方法
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return YOUR_DATA_ARRAY.COUNT
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return YOUR_DATA_ARRAY[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print(YOUR_DATA_ARRAY[row])
}
UIPickerViewDataSource
和 picker.dataSource = self
。 - el3ankaboot只需隐藏/显示您的uipickerview
。在故事板中将选择器添加为主视图的子视图,但保持其隐藏状态。单击该按钮即可显示它。
添加带有完成按钮的工具栏以再次隐藏选择器。这里是一个链接