Last active
July 31, 2023 03:55
-
-
Save BrunoCerberus/1cb807584720621513cd856ed7fa7aea to your computer and use it in GitHub Desktop.
SwiftUI Custom Environment Values
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 | |
/// 1. Create the environment key to hold the custom caption background color. | |
private struct CaptionColorKey: EnvironmentKey { | |
static let defaultValue = Color(.secondarySystemBackground) | |
} | |
/// 2. Extend the environment to provide access to the custom caption background color. | |
extension EnvironmentValues { | |
var captionBackgroundColor: Color { | |
get { self[CaptionColorKey.self] } | |
set { self[CaptionColorKey.self] = newValue } | |
} | |
} | |
/// 3. Define a custom ViewModifier to apply the caption background color to a view. | |
struct CaptionBackgroundColor: ViewModifier { | |
// Retrieve the custom caption background color from the environment. | |
@Environment(\.captionBackgroundColor) var backgroundColor: Color | |
// Apply the custom caption background color to the view's background. | |
func body(content: Content) -> some View { | |
content | |
.background(backgroundColor) | |
} | |
} | |
/// 4. Usage: Create an extension on View to provide a modifier function for applying the custom caption background color. | |
extension View { | |
// A convenient function to apply the custom caption background color to a view. | |
func captionBackgroundColor(_ color: Color) -> some View { | |
self.modifier(CaptionBackgroundColor()) | |
.environment(\.captionBackgroundColor, color) | |
} | |
} | |
/// 5. Usage: Create a TestView that demonstrates how to use the custom caption background color. | |
struct TestView: View { | |
// Access the custom caption background color from the environment. | |
@Environment(\.captionBackgroundColor) var backgroundColor | |
var body: some View { | |
VStack { | |
// Apply the custom caption background color to the Text view using the captionBackgroundColor modifier. | |
Text("Hello, world!") | |
.captionBackgroundColor(.yellow) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment