[英]How to create an alert with DatePicker in SwiftUI
What you want is actually discouraged by Apple (according to this answer ). Apple 实际上不鼓励您想要什么(根据此答案)。 This is probably why you can't find any examples yourself.
这可能就是你自己找不到任何例子的原因。
Here is a possible solution:这是一个可能的解决方案:
struct ContentView: View {
@State var selectedDate = Date()
static let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("yyMMddhhmm")
return formatter
}()
var body: some View {
VStack {
Text("Selected date: \(selectedDate, formatter: Self.formatter)")
Button("Show action sheet") {
self.showDatePickerAlert()
}
}
}
func showDatePickerAlert() {
let alertVC = UIAlertController(title: "\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: .actionSheet)
let datePicker: UIDatePicker = UIDatePicker()
alertVC.view.addSubview(datePicker)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
self.selectedDate = datePicker.date
}
alertVC.addAction(okAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alertVC.addAction(cancelAction)
if let viewController = UIApplication.shared.windows.first?.rootViewController {
viewController.present(alertVC, animated: true, completion: nil)
}
}
}
This uses the "\\n\\n\\n\\n\\n\\n\\n\\n\\n"
hack from this answer .这使用了这个答案中的
"\\n\\n\\n\\n\\n\\n\\n\\n\\n"
hack。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.