我的场景,我正在尝试创建按钮单击以打开UIPickerView
并选择选择器数据以快速显示按钮标题。在这里,我还想将Toolbar
添加到pickerview控制器中。
let button = UIButton(type: .custom)
button.setTitle("",for: .normal)
button.frame = CGRect(x: CGFloat(amount_textfield.frame.size.width - 9), y: CGFloat(5), width: CGFloat(9), height: CGFloat(20))
button.addTarget(self, action: #selector(self.refresh), for: .touchUpInside)
amount_textfield.leftView = button
amount_textfield.leftViewMode = .always
@IBAction func refresh(_ sender: Any) {
// Here, I need to execute picker view
}
答案 0 :(得分:0)
您必须遵循的几个步骤:
创建最初隐藏的UIPickerView
并设置其delegate
和dataSource
@IBOutlet weak var pickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
}
具有用于此选择器视图的数据源数组
class ViewController: UIViewController {
var array = [String]()
}
extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return array.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return array[row]
}
}
在按下按钮时取消隐藏选择器视图
pickerView.isHidden = false
集成选择器视图的委托方法pickerView(_:didSelectRow:inComponent:)
。选择行后,将按钮的标题设置为数据源数组中元素的元素,位于选定的索引row
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
button.setTitle(array[row], for: .normal)
}
可选:隐藏选择器视图
pickerView.isHidden = true