Skip to content

Instantly share code, notes, and snippets.

@usk2000
Created August 9, 2020 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usk2000/95fdcd327c5fe22aa892d615721de0d9 to your computer and use it in GitHub Desktop.
Save usk2000/95fdcd327c5fe22aa892d615721de0d9 to your computer and use it in GitHub Desktop.
EnvironmentObjectとBinding
//: 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