PickerView调用点击时间
时间: 2023-09-13 18:05:12 浏览: 95
PickerView可以通过实现`UIPickerViewDelegate`中的`pickerView(_:didSelectRow:inComponent:)`方法来响应用户的点击事件。该方法会在用户点击PickerView中某一行时被调用,参数`row`表示用户所选行的索引,而参数`component`表示用户所选列的索引。例如,下面的代码展示了一个PickerView,并在用户点击某一行时弹出一个UIAlertController提示框。
```swift
class MyViewController: UIViewController, UIPickerViewDelegate {
let data = ["Option 1", "Option 2", "Option 3"]
var pickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
pickerView = UIPickerView()
pickerView.delegate = self
view.addSubview(pickerView)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
pickerView.frame = CGRect(x: 0, y: 100, width: view.bounds.width, height: 200)
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let alertController = UIAlertController(title: "Selected", message: "You selected \(data[row])", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return data[row]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return data.count
}
}
```
阅读全文