Created
August 9, 2020 06:23
-
-
Save usk2000/95fdcd327c5fe22aa892d615721de0d9 to your computer and use it in GitHub Desktop.
EnvironmentObjectとBinding
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
//: A UIKit based Playground for presenting user interface | |
import UIKit | |
import PlaygroundSupport | |
import SwiftUI | |
struct ContentView: View { | |
@EnvironmentObject var countSetting: CountSetting | |
var body: some View { | |
NavigationView { | |
List { | |
NavigationLink.init(destination: AnotherView()) { | |
ChildView(value: .init(get: { self.countSetting.count }, set: { _ in })) | |
} | |
} | |
} | |
} | |
} | |
struct ChildView: View { | |
@Binding var value: Int | |
var body: some View { | |
HStack { | |
Text("回数") | |
Spacer() | |
Text("\(value)") | |
} | |
.navigationBarTitle("親View", displayMode: .inline) | |
} | |
} | |
struct AnotherView: View { | |
@EnvironmentObject var countSetting: CountSetting | |
var body: some View { | |
VStack { | |
Spacer() | |
Text("回数を") | |
Button.init("増やす") { | |
self.countSetting.count += 1 //1増やす | |
}.padding() | |
Spacer() | |
}.navigationBarTitle("もう一つのView", displayMode: .inline) | |
} | |
} | |
/// classにする | |
class CountSetting: ObservableObject { | |
@Published var count: Int = 0 | |
} | |
// Present the view controller in the Live View window | |
let contentView = ContentView() | |
.environmentObject(CountSetting()) | |
PlaygroundPage.current.liveView = UIHostingController(rootView: contentView) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment