2

I am trying to Bind UIDatePicker with a variable that is coming straight from Server but the issue is variable has a type of TimeStamp and UIDatePicker requires a type of Date.

if(self.shouldShowDatePicker)
{
    DatePicker(selection:self.$taskData.fields[index].dateField.valueTime , displayedComponents: .date)
    Text("DatePicker")
}

Now I know that this variable self.$taskData.fields[index].dateField.valueTime is of TimeStamp type, and since you can see that this variable belongs to a very complex array of fields so I cannot alter the structure. Please let me know what is the possible solution. Thanks

2 Answers 2

2

You can wrap it in dynamic Binding, like the following

if(self.shouldShowDatePicker)
{
   DatePicker(selection: Binding<Date>(
       get: { Date(timeIntervalSince1970: self.taskData.fields[index].dateField.valueTime) },
       set: { self.taskData.fields[index].dateField.valueTime = $0.timeIntervalSince1970 } ), 
       displayedComponents: [.date]) { Text("DatePicker") }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I got this error 'Generic parameter 'SelectionValue' could not be inferred' after adding your piece of code.
@Najam, I wrote just inline from your snapshot to show the idea of binding, try updated. Compiling errors might be just due to typos.
@Najam, tested with self.timestamp replaced your model - compiled & worked. Xcode 11.2 / iOS 13.2
0

An extension should do the trick

extension Double {
    var _boundDate: Date {
        get {
            return Date(timeIntervalSince1970: self )
        }
        set {
            self = newValue.timeIntervalSince1970
        }
    }
    public var boundDate: Date {
        get {
            return _boundDate
        }
        set {
            _boundDate = newValue
        }
    }
}

Your binding on the DatePicker would look like this

self.$taskData.fields[index].dateField.valueTime.boundDate

1 Comment

@Najam What type is valueTime? Is it a Double or TimeInterval? Is TimeStamp a Custom class? If so, you can replace Double on my code with TimeStamp and adjust the _boundDate get set methods to point to the seconds in the TimeStamp class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.