Created
September 29, 2021 17:45
-
-
Save seanwoodward/01c372a04a7fef7719001e092c1889c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct CustomDatePickerExample: View { | |
@Binding private var currentDate: Date | |
@State private var currentYear: Int | |
@State private var currentMonth: Int | |
var body: some View { | |
VStack (spacing: 12) { | |
HStack { | |
Spacer() | |
Button { | |
guard currentYear > 0 else { return } | |
currentYear -= 1 | |
} label: { | |
Image(systemName: "chevron.left") | |
}.disabled(1 == currentYear) | |
Text(currentYear.formatted(.number.grouping(.never))) | |
Button { | |
currentYear += 1 | |
} label: { | |
Image(systemName: "chevron.right") | |
} | |
Spacer() | |
} | |
HStack { | |
Text(Calendar.autoupdatingCurrent.monthSymbols[currentMonth - 1]) | |
Spacer() | |
Button { | |
guard currentMonth > 1 else { return } | |
currentMonth -= 1 | |
} label: { | |
Image(systemName: "chevron.left") | |
}.disabled(1 == currentMonth) | |
Button { | |
guard currentMonth < 12 else { return } | |
currentMonth += 1 | |
} label: { | |
Image(systemName: "chevron.right") | |
}.disabled(12 == currentMonth) | |
} | |
Text(currentDate.formatted(date: .abbreviated, time: .omitted)) | |
} | |
.padding() | |
} | |
init(currentDate: Binding<Date>) { | |
self._currentDate = currentDate | |
let date = currentDate.wrappedValue | |
let year: Int = Calendar.autoupdatingCurrent.component(.year, from: date) | |
let month: Int = Calendar.autoupdatingCurrent.component(.month, from: date) | |
self._currentYear = State(initialValue: year) | |
self._currentMonth = State(initialValue: month) | |
} | |
} | |
struct ParentView: View { | |
@State var currentDate: Date = Date() | |
var body: some View { | |
CustomDatePickerExample(currentDate: $currentDate) | |
} | |
} | |
struct CustomDatePickerExample_Previews: PreviewProvider { | |
static var previews: some View { | |
ParentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment