有没有一种格式化日期的方法?(从图片中箭头指示的位置开始)我知道它是根据语言环境格式化的,但是我有没有一种格式化它的方法?
struct ContentView: View {
@State private var selectedDate = Date()
var body: some View {
Form {
DatePicker(selection: $selectedDate, in: ...Date(), displayedComponents: .date) {
Text("From*")
}
}
}
}
答案 0 :(得分:0)
我能想到的唯一方法是创建自己的自定义DatePicker视图,并在TextField上使用onAppear来更新@State selectedDateText:String变量以在TextField中显示。感觉就像是骇客,我几乎不好意思发布它,但它确实有效。我一般是Swift和iOS编程的新手,所以我敢肯定有人会提供更好的答案,因此我将尽其所能提供此功能。我的自定义视图是这样的:
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()
}
}
}
}
编辑:我弄清楚了从哪里获得私有var代码。来自这篇文章:How to detect a value change of a Datepicker using SwiftUI and Combine?