gpt4 book ai didi

ios - 从 DatePicker SwiftUI 更改选定的日期格式

转载 作者:行者123 更新时间:2023-12-01 22:51:56 24 4
gpt4 key购买 nike

有没有办法格式化日期?(从图中箭头指示的位置开始)我知道它是根据区域设置格式化的,但是有没有办法自己格式化它?

enter image description here

struct ContentView: View {

@State private var selectedDate = Date()

var body: some View {
Form {

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

最佳答案

我能想到的唯一方法是创建我自己的自定义 DatePicker View ,并在 TextField 上使用 onAppear 来更新 @State selectedDateText: String 变量以在 TextField 中显示。这感觉就像是黑客攻击,我几乎不好意思发布它,但它确实有效。总的来说,我对 Swift 和 iOS 编程还是个新手,所以我相信有人会提出更好的答案,所以我将提供这个有值(value)的答案。我的自定义 View 是这样的:

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

编辑:我找到了私有(private) var 代码的来源。来自这篇文章:How to detect a value change of a Datepicker using SwiftUI and Combine?

关于ios - 从 DatePicker SwiftUI 更改选定的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59051670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com