Last active
October 14, 2020 16:15
-
-
Save JanC/719b23dce0e8c084d8102bc065aafdec to your computer and use it in GitHub Desktop.
This file contains 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 | |
/// If _anything_ changes in the `MainView` (e.g. Timer update), its `var body` is re-created and therefore a new instance of `DetailsView(presenter: DetailsViewPresenter())` is created (even if it is already pushed) | |
/// A new instance of `DetailsViewPresenter` has `isChecked` set to false so the checkbox is unchecked even if view is already presented | |
struct MainView: View { | |
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() | |
let formatter: DateFormatter = { | |
let f = DateFormatter() | |
f.dateFormat = "HH:mm:ss" | |
return f | |
}() | |
@State var currentTime = "00:00:00" | |
var body: some View { | |
NavigationView { | |
VStack(spacing: 20) { | |
Text("\(currentTime)") | |
.onReceive(timer) { input in | |
currentTime = formatter.string(from: input) | |
} | |
NavigationLink(destination: DetailsView(presenter: DetailsViewPresenter()), | |
label: { Text("@ObservedObject") }) | |
NavigationLink(destination: DetailsViewStateObject(presenter: DetailsViewPresenter()), | |
label: { Text("@StateObject") }) | |
NavigationLink(destination: DetailsViewWithState(), | |
label: { Text("@State") }) | |
} | |
.navigationTitle("Main") | |
} | |
} | |
} | |
// MARK: - Child view | |
class DetailsViewPresenter: ObservableObject { | |
@Published var isChecked = false | |
deinit { | |
print("deinit \(self)") | |
} | |
} | |
struct DetailsView: View { | |
@ObservedObject var presenter: DetailsViewPresenter | |
var body: some View { | |
VStack { | |
Toggle(isOn: $presenter.isChecked) { | |
Text("Hello World") | |
} | |
.padding() | |
} | |
.navigationTitle("@ObservedObject") | |
} | |
} | |
struct DetailsViewStateObject: View { | |
@StateObject var presenter: DetailsViewPresenter | |
var body: some View { | |
VStack { | |
Toggle(isOn: $presenter.isChecked) { | |
Text("Hello World") | |
} | |
.padding() | |
} | |
.navigationTitle("@StateObject") | |
} | |
} | |
struct DetailsViewWithState: View { | |
@State var isChecked = false | |
var body: some View { | |
VStack { | |
Toggle(isOn: $isChecked) { | |
Text("Hello World") | |
} | |
.padding() | |
} | |
.navigationTitle("@State") | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
MainView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment