Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Created March 29, 2025 08:44
Show Gist options
  • Save Koshimizu-Takehito/b9033ef5b653b211c5eef2cf1f2897ab to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/b9033ef5b653b211c5eef2cf1f2897ab to your computer and use it in GitHub Desktop.
EnvironmentValuesが大域変数ではないことを示すサンプルコード2
import SwiftUI
extension EnvironmentValues {
@Entry var customStringValue = "Goodbye, world!"
}
struct ContentView: View {
var body: some View {
RepRepresentable()
.environment(\.customStringValue, "Hello, world!")
}
}
struct FooView: View {
@Environment(\.customStringValue) var customValue: String
var action: () -> Void
var body: some View {
VStack {
Button(customValue, action: action)
.font(.largeTitle.bold())
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.background)
}
}
struct RepRepresentable: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> ViewController {
ViewController()
}
func updateUIViewController(_: ViewController, context: Context) {}
}
final class ViewController: UIViewController {
override func loadView() {
view = UIHostingConfiguration {
FooView { [weak self] in
self?.present(ViewController(), animated: true)
}
}
.margins(.all, EdgeInsets())
.makeContentView()
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment