Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an alert with DatePicker in SwiftUI

Tags:

ios

swiftui

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

I want the following view.

Thanks for the help

enter image description here

like image 344
Akash Chaudhary Avatar asked Nov 07 '22 08:11

Akash Chaudhary


1 Answers

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)
        }
    }
}

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

like image 94
pawello2222 Avatar answered Nov 14 '22 23:11

pawello2222