[英]SwiftUI TextField Date Binding
Hmmm.嗯。 I'm not doing very well with these bindings.
我对这些绑定做得不是很好。
struct RecordForm: View
{
@State var record: Record
var body: some View
{
TextField("date", text: Binding($record.recordDate!)))
}
}
I want to convert this Date to a String.我想将此日期转换为字符串。 In regular Swift I would just call my extension
在常规 Swift 中,我只会调用我的扩展程序
record.recordDate.mmmyyy()
but I cannot find the right syntax or even the right place to do the conversion.但我找不到正确的语法,甚至找不到进行转换的正确位置。
If I try to put the code in the body or the struct I just get a pile of errors.如果我尝试将代码放入正文或结构中,我只会收到一堆错误。
Is there any easy to read documentation on this subject?有没有关于这个主题的易于阅读的文档?
The answer by nine stones worked nicely, although I had to tweak the code slightly to get it to work for me with an NSManagedObject:九块石头的答案效果很好,尽管我不得不稍微调整代码才能让它与 NSManagedObject 一起工作:
struct RecordDate: View
{
@State var record: Record //NSManagedObject
var body: some View {
let bind = Binding<String>(
get: {self.$record.recordDate.wrappedValue!.dateString()},
set: {self.$record.recordDate.wrappedValue = dateFromString($0)}
)
return HStack {
Text("Date:")
TextField("date", text: bind)
}
}
}
//dateString is a date extension that returns a date as a string
//dateFromString is a function that returns a string from a date
Documentation is hard to find and Apple's really ucks.文档很难找到,而且 Apple 真的很烂。
Try to create a custom binding.尝试创建自定义绑定。
extension Date {
func mmyyy() -> String { "blah" }
static func yyymm(val: String) -> Date { Date() }
}
struct RecordForm: View {
struct Record {
var recordDate: Date
}
@State var record = Record(recordDate: Date())
var body: some View {
let bind = Binding(
get: { self.record.recordDate.mmyyy() },
set: { self.record.recordDate = Date.yyymm(val: $0)}
)
return VStack {
TextField("date", text: bind)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.