如何在 SwiftUI 中使用 DatePicker 创建警报 [英] How to create an alert with DatePicker in SwiftUI

查看:23
本文介绍了如何在 SwiftUI 中使用 DatePicker 创建警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在警报视图或操作表视图中显示 DatePicker,但我找不到任何资源来执行此操作.

I want to display DatePicker in alert view or action sheet view , but I could not find any resources to do it.

我想要以下视图.

感谢您的帮助

推荐答案

你想要的其实是 Apple 不鼓励的(根据 this answer).这可能就是你自己找不到任何例子的原因.

What you want is actually discouraged by Apple (according to this answer). 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)
        }
    }
}

这使用了 /56607279/8697793">这个答案.

This uses the "\n\n\n\n\n\n\n\n\n" hack from this answer.

这篇关于如何在 SwiftUI 中使用 DatePicker 创建警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆