0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SwiftUI】DatePickerで日付を選択する

Posted at

まえがき

この記事はSwift独学者による備忘録です。
万が一誤った記載がある場合は、コメントでご指摘いただけると幸いですm(_ _)m

確認環境

XCode Version 15.4
MacOS Sonoma 14.4.1

日付を選択する方法

日付の選択方法はいくつかありますが、この記事ではDatePickerを使用して「年月日」を選択する方法をまとめます。

コード例

ContentView.swift
import SwiftUI

struct ContentView: View {
    @State private var selectedDate: Date? = nil
    @State private var isDatePickerPresented = false

    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                HStack {
                    Text("誕生日:")
                    Spacer()
                    Text(selectedDate != nil ? formattedDate(selectedDate!) : "選択")
                        .foregroundColor(.gray)
                }
                .padding()
                .background(Color(UIColor.secondarySystemBackground))
                .cornerRadius(10)
                .onTapGesture {
                    isDatePickerPresented = true
                }

                Spacer()
            }
            .padding()
            .navigationTitle("誕生日を選択")
            .sheet(isPresented: $isDatePickerPresented) {
                DatePickerView(selectedDate: $selectedDate)
            }
        }
    }

    func formattedDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.locale = Locale(identifier: "ja_JP") // 選択した日付を日本語表記にする
        return formatter.string(from: date)
    }
}

struct DatePickerView: View {
    @Binding var selectedDate: Date?
    @State private var tempSelectedDate = Date()
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        VStack {
            DatePicker("Select a date", selection: $tempSelectedDate, displayedComponents: .date)
                .datePickerStyle(WheelDatePickerStyle())
                .labelsHidden()
                .padding()
                .environment(\.locale, Locale(identifier: "ja_JP")) // 選択する日付を日本語表記にする
            
            Button("Done") {
                selectedDate = tempSelectedDate
                dismiss()
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10)
        }
    }
}

選択前 日付選択画面 選択後

あとがき

簡単にDatePickerで日付を選択する方法をまとめました。
今後も捕捉事項があれば随時更新していきます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?