Created
March 29, 2025 08:44
-
-
Save Koshimizu-Takehito/b9033ef5b653b211c5eef2cf1f2897ab to your computer and use it in GitHub Desktop.
EnvironmentValuesが大域変数ではないことを示すサンプルコード2
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 | |
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