Search code examples
dateswiftuinsmanagedobject

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

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?


Solution

  • Documentation is hard to find and Apple's really ucks.

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