简体   繁体   中英

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?

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:

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.

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

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