[英]How to get data from UIDatePicker countDownTimer mode
我在 AlertController 上有处于 countDownTimer 模式的 UIDatePicker。 我想保存值,用户在按下设置按钮时会选择变量。 我该怎么做? 我现在的代码:
func showAlert() {
let vc = UIViewController()
vc.preferredContentSize = CGSize(width: 250,height: 300)
let pickerView = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 250, height: 300))
pickerView.datePickerMode = .countDownTimer
vc.view.addSubview(pickerView)
let alert = UIAlertController(title: "Sleep Timer", message: "Please, choose hours and minutes", preferredStyle: UIAlertController.Style.alert)
alert.setValue(vc, forKey: "contentViewController")
alert.addAction(UIAlertAction(title: "Set", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
通常,您可以访问选择器的countDownDuration属性来获取秒值。
它的范围在 0 到 86,340 秒之间。
let seconds = pickerView.countDownDuration
对于您所需的情况,您有很多选择。 其中2个是:
func showAlert() {
let vc = UIViewController()
vc.preferredContentSize = CGSize(width: 250,height: 300)
let pickerView = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 250, height: 300))
pickerView.datePickerMode = .countDownTimer
//Your required line
pickerView.addTarget(self, action: #selector(onDurationChanged), for: .valueChanged)
vc.view.addSubview(pickerView)
let alert = UIAlertController(title: "Sleep Timer", message: "Please, choose hours and minutes", preferredStyle: UIAlertController.Style.alert)
alert.setValue(vc, forKey: "contentViewController")
alert.addAction(UIAlertAction(title: "Set", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
@objc private func onDurationChanged(_ picker: UIDatePicker) {
let seconds = picker.countDownDuration
//Do something with duration
}
您可以为选择器选择创建一个小型 VC,然后您可以更好地分离关注点:
class PickerViewController: UIViewController {
var duration: TimeInterval = 0
let pickerView: UIDatePicker = {
let picker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 250, height: 300))
picker.datePickerMode = .countDownTimer
picker.addTarget(self, action: #selector(onDurationChanged), for: .valueChanged)
return picker
}()
@objc private func onDurationChanged(_ picker: UIDatePicker) {
duration = picker.countDownDuration
}
}
class ViewController: UIViewController {
func showAlert() {
let vc = PickerViewController()
vc.preferredContentSize = CGSize(width: 250,height: 300)
let alert = UIAlertController(title: "Sleep Timer", message: "Please, choose hours and minutes", preferredStyle: UIAlertController.Style.alert)
alert.setValue(vc, forKey: "contentViewController")
alert.addAction(UIAlertAction(title: "Set", style: .default, handler: { action in
let seconds = vc.duration
//Do something.
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.