简体   繁体   中英

Change selected date format from DatePicker SwiftUI

Is there a way to format the date?(from the position indicated by the arrow in the picture) I know it is formatted based on the locale but is there a way to format it myself?

在此处输入图像描述

struct ContentView: View {

    @State private var selectedDate = Date()

    var body: some View {
        Form {

            DatePicker(selection: $selectedDate, in: ...Date(), displayedComponents: .date) {
                Text("From*")
            }
        }
    }
}

The only way I could figure to accomplish this is to create my own custom DatePicker view and use onAppear on the TextField to update an @State selectedDateText: String variable for displaying in the TextField. This feels like a hack and I'm almost embarrassed to post it but it works. I'm new at Swift and iOS programming in general so I'm sure someone will come along with a better answer so I'll offer this for what it's worth. My custom view is something like this:

struct CustomDatePicker: View {
  @Binding var date: Date

  @State private var showPicker: Bool = false
  @State private var selectedDateText: String = "Date"

  private var selectedDate: Binding<Date> {
    Binding<Date>(get: { self.date}, set : {
        self.date = $0
        self.setDateString()
    })
  } // This private var I found… somewhere. I wish I could remember where

  // To take the selected date and store it as a string for the text field
  private func setDateString() {
    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM dd, yyyy"

    self.selectedDateText = formatter.string(from: self.date)
  }

  var body: some View {
    VStack {
        HStack {
            Text("Date:")
                .frame(alignment: .leading)
            
            TextField("", text: $selectedDateText)
                .onAppear() {
                    self.setDateString()
                }
                .disabled(true)
                .onTapGesture {
                    self.showPicker.toggle()
                }
            .multilineTextAlignment(.trailing)
        }            
        
        if showPicker {
            DatePicker("", selection: selectedDate,
            displayedComponents: .date)
            .datePickerStyle(WheelDatePickerStyle())
            .labelsHidden()
        }
    }
  }
}

EDIT: I figured out where I got the private var code. It was from this post: How to detect a value change of a Datepicker using SwiftUI and Combine?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM