Created
September 16, 2019 10:45
-
-
Save webcpu/23ce24a6add499fba968ecd080b640eb 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 | |
import Combine | |
| |
struct FlightBookingView: View { | |
@ObservedObject var model: FlightBookingViewModel | |
var body: some View { | |
NavigationView { | |
Form { | |
DatePicker(selection: $model.departureDate, in: model.departureDateRange, displayedComponents: .date) { | |
Text("Departure Date") | |
} | |
DatePicker(selection: $model.returnDate, in: model.returnDateRange, displayedComponents: .date) { | |
Text("Return Date") | |
} | |
Text(model.message) | |
} | |
.listStyle(GroupedListStyle()) | |
.navigationBarItems(trailing: Button(action: { | |
print("") | |
}) | |
{ Text("Submit") } | |
) | |
} | |
} | |
} | |
| |
struct FlightBookingView_Previews: PreviewProvider { | |
static var previews: some View { | |
FlightBookingView(model: FlightBookingViewModel().connect()) | |
} | |
} | |
| |
class FlightBookingViewModel: ObservableObject { | |
// Input | |
@Published var departureDate: Date = Date() | |
@Published var returnDate: Date = Calendar.current.date(byAdding: .day, value: 1, to: Date())! | |
// Output | |
@Published var dates: (Date, Date) = (Date(), Date()) | |
@Published var message: String = "" | |
var datesCancellable: AnyCancellable! | |
var returnCancellable: AnyCancellable! | |
var departureDateRange: ClosedRange<Date> { | |
return Date()...Date.distantFuture | |
} | |
var returnDateRange: ClosedRange<Date> { | |
return departureDate...Date.distantFuture | |
} | |
func debug(_ dates: (Date, Date)) -> String { | |
let dateToString = { (date: Date) -> String in | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "dd-MM-yyyy" | |
return dateFormatter.string(from: date) | |
} | |
let d = dateToString(dates.0) | |
let r = dateToString(dates.1) | |
return "\(d) - \(r)" | |
} | |
func connect() -> Self { | |
self.datesCancellable = Publishers.CombineLatest($departureDate, $returnDate) | |
.sink(receiveValue: {_ in | |
if self.departureDate > self.returnDate { | |
self.returnDate = self.departureDate | |
} | |
self.message = self.debug((self.departureDate, self.returnDate)) | |
}) | |
return self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment