[SwiftUI] DatePickerを作る

簡単なデートピッカーを作る

    var body: some View {
        DatePicker(selection: $theDate, label: {Text("日時")})
            .padding(50)
    }

日本語・和暦表示

        DatePicker(selection: $theDate, label: {Text("日時")})
            .environment(\.locale, Locale(identifier: "ja_JP"))
            .environment(\.calendar, Calendar(identifier: .japanese))
            .frame(height: 50)
            .padding()

選択できる日付の範囲制限

    @State var theDate = Date()
    
    var dateCloseRange: ClosedRange<Date>{
        let min = Calendar.current.date(byAdding: .day, value: -7, to: Date())!
        let max = Calendar.current.date(byAdding: .month, value: 1, to: Date())!
        return min...max
    }
    
    var body: some View {
        DatePicker(selection: $theDate, in: dateCloseRange, label: {Text("日時")})
            .environment(\.locale, Locale(identifier: "ja_JP"))
            .frame(height: 50)
            .padding()
    }

日時データの表示

@State var theDate = Date()
    
    var dateFormat1: DateFormatter {
        let df = DateFormatter()
        df.locale = Locale(identifier: "ja_JP")
        df.dateStyle = .full
        df.timeStyle = .short
        return df
    }
    
    var dateFormat2: DateFormatter {
        let df = DateFormatter()
        df.locale = Locale(identifier: "ja_JP")
        df.calendar = Calendar(identifier: .japanese)
        df.dateFormat = "令和yy(YYYY)年M月dd日(E)HH時mm分"
        return df
    }
    
    
    var body: some View {
        
        VStack {
            Text(dateFormat1.string(from: theDate))
            Text(dateFormat2.string(from: theDate))
            DatePicker(selection: $theDate, label: {EmptyView()})
                .environment(\.locale, Locale(identifier: "ja_JP"))
                .frame(width: 200, height: 40)
                .padding()
        }
    }

日付と時刻の2つのコンポーネントに分けて表示

    @State var theDate = Date()
        
    var body: some View {
        
        VStack(alignment: .leading, spacing: 10) {
            DatePicker("日付", selection: $theDate, displayedComponents: .date)
                .environment(\.locale, Locale(identifier: "ja_JP"))
                .frame(width: 200)
            DatePicker("時刻", selection: $theDate, displayedComponents: .hourAndMinute)
                .frame(width: 200)
            Text(theDate.description(with: Locale(identifier: "ja_JP")))
                .font(.footnote)
        }
        .padding()
        .border(Color.gray, width: 1)
    }

これはapple クソすげーわ
どうやって開発してんだこれ?