Last active
November 11, 2024 13:58
-
-
Save lucianoschillagi/13e08236bb2e498a43520a6055c7c318 to your computer and use it in GitHub Desktop.
Creating custom environment value in SwiftUI
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 | |
struct ContentView: View { | |
@Environment(\.myCustomValue) private var myCustomValue | |
var body: some View { | |
Text(myCustomValue).font(.title2) | |
} | |
} | |
// Creating a custom environment value extending the EnvironmentValues struct | |
extension EnvironmentValues { | |
@Entry var myCustomValue: String = "Your custom environment value goes here" | |
} | |
extension View { | |
func myCustomValue(_ myCustomValue: String) -> some View { | |
environment(\.myCustomValue, myCustomValue) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment