[英]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.