반응형
@Environment 환경변수를 시스템에서 제공된 것 외에 사용자가 지정해서 사용해야 할 경우가 있습니다.
방법은 EnvironmentKey 프로토콜을 준수하도록 설정하면 됩니다.
참고 : https://developer.apple.com/documentation/swiftui/environmentvalues
// 사용할 키 정의
struct MyEnvironmentKey: EnvironmentKey {
static let defaultValue: String = "Default value"
}
// 해당 변수에 대한 getter, setter 정의
extension EnvironmentValues {
var myCustomValue: String {
get { self[MyEnvironmentKey.self] }
set { self[MyEnvironmentKey.self] = newValue }
}
}
// 사용할 뷰
struct ContentView: View {
@Environment(\.myCustomValue) var myCustomValue: String
var body: some View {
...
}
}
// 기본 사용방법
ContentView().environment(\.myCustomValue, "Test")
// 간편하게 사용하기 위해 View 확장
extension View {
func myCustomValue(_ myCustomValue: String) -> some View {
environment(\.myCustomValue, myCustomValue)
}
}
// 간편하게 사용
ContentView().myCustomValue("Test")
반응형
'SwiftUI > Controls & Tips' 카테고리의 다른 글
SwiftUI 에서 Background나 Foreground 진입시 처리 (0) | 2024.01.05 |
---|---|
SegmentView (0) | 2023.12.30 |
Keyboard Height 계산해서 Publisher 하기 (0) | 2023.12.13 |
TextField에 clearButton 추가하기 (0) | 2023.12.13 |
Warning "Non-constant range: argument must be an integer literal" (0) | 2023.12.07 |
foregroundColor vs tint (0) | 2023.10.28 |
SwiftUI 아이폰 회전시 Landscape, Portrait 이벤트 (0) | 2023.10.24 |
SwiftUI Color Hex 값으로 생성하기 (0) | 2023.10.08 |