반응형
@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")반응형
'Dev Study > iOS' 카테고리의 다른 글
| 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 |
| SFSymbol의 Monochrome, Hierarchical, Palette, Multicolor Mode (1) | 2023.12.05 |
| @AppStorage에 Date 타입과 Array 타입 사용하기 (0) | 2023.12.04 |
| PassthroughSubject vs CurrentValueSubject (1) | 2023.12.01 |
| UIView -> UIImage (0) | 2023.11.15 |
| iOS 16.4 이후부터 WebView 디버깅 하기 (0) | 2023.11.15 |


