forked from LoopKit/LoopKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpandableDatePicker.swift
More file actions
65 lines (58 loc) · 1.88 KB
/
ExpandableDatePicker.swift
File metadata and controls
65 lines (58 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// ExpandableDatePicker.swift
// LoopKitUI
//
// Created by Anna Quinlan on 8/12/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import SwiftUI
public struct ExpandableDatePicker: View {
@State var dateShouldExpand = false
@Binding var date: Date
let placeholderText: String
let pickerRange: ClosedRange<Date>
@State var userDidTap: Bool = false
public init (
with date: Binding<Date>,
pickerRange: ClosedRange<Date>? = nil,
placeholderText: String = ""
) {
_date = date
self.placeholderText = placeholderText
let today = Date()
self.pickerRange = pickerRange ?? today.addingTimeInterval(-.hours(24))...today
}
public var body: some View {
VStack(spacing: 0) {
HStack {
dateFieldText
Spacer()
}
.padding()
.frame(minWidth: 0, maxWidth: .infinity).onTapGesture {
self.userDidTap = true
// Hack to refresh binding
self.date = Date(timeInterval: 0, since: self.date)
self.dateShouldExpand.toggle()
}
if dateShouldExpand {
DatePicker("", selection: $date, in: pickerRange, displayedComponents: .date)
.labelsHidden()
}
}
}
private var dateFieldText: some View {
if userDidTap {
return Text(dateFormatter.string(from: date))
// Show the placeholder text if user hasn't interacted with picker
} else {
return Text(placeholderText).foregroundColor(Color(UIColor.lightGray))
}
}
private var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeZone = TimeZone.current
return formatter
}
}