Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - SwiftUI] 튜토리얼 - 12. EnvironmentValues, @Environment, EnvironmentKey 개념 본문

iOS 튜토리얼 (SwiftUI)

[iOS - SwiftUI] 튜토리얼 - 12. EnvironmentValues, @Environment, EnvironmentKey 개념

jake-kim 2022. 7. 14. 22:05

EnvironmentValues

https://developer.apple.com/documentation/swiftui/environmentvalues

  • superview에서 darkmode로 설정하면 subviews들도 모두 darkmode로 변할 수 있는 기능을 EnvironmentValues로 제어가 가능
  • Swift에서는 개별 클래스로 관리하였지만, SwiftUI에서는 모두 Environment를 통해서 모두 접근이 가능
  • 가장 대표적인 값은, 지금 지역을 알 수 있는 locale과 layoutDirection, undoManager 등 접근 가능

ex) superview에서 `colorScheme`값을 dark로 지정하면 subview들은 자동으로 dark mode로 변경

  • EnvironmentValues 종류
    • editMode
    • colorScheme
    • timeZone
    • locale
    • calendar
    • layoutDirection
    • sizeCategory
    • undoManager
    • 등등

@Environment

https://developer.apple.com/documentation/swiftui/environment

  • propertyWrapper이며, environment 값을 읽을 때 사용
  • EnvironmentValues를 사용할 때 @Environment를 이용
import SwiftUI

struct ContentView: View {
  @Environment(\.colorScheme) var colorScheme: ColorScheme
  
  var body: some View {
    if colorScheme == .dark {
      Text("dark!")
        .padding()
    } else {
      Text("white!")
        .padding()
    }
  }
}

EnvironmentKey

https://developer.apple.com/documentation/swiftui/environmentkey

  • Environment를 커스텀하여, 시스템에서 제공해주는 것 뿐만이 아닌 직접 변수를 추가하여 사용이 가능

ex) primaryColor 환경변수 값 만들기

  • Key 추가
    • EnvironmentKey를 상속받고, defaultValue를 선언
// 1. EnvironmentKey를 상속
private struct MyColorKey: EnvironmentKey {
  
  // 2. defaultValue로 해당 키에 대한 기본값을 지정하고 값의 타입을 결정
  static let defaultValue = Color(.blue)
}
  • EnvironmentValues 추가
    • extension을 이용하여 EnvironmentValues에 직접 접근이 가능할 이름의 computed property를 선언
extension EnvironmentValues {
  var primaryColor: Color {
    get { self[MyColorKey.self] }
    set { self[MyColorKey.self] = newValue }
  }
}
  • 사용하는 쪽
    • 위에서 선언한 primaryColor를 이용하여 사용
struct ContentView: View {
  @Environment(\.primaryColor) var myColor: Color
  
  var body: some View {
    Text("dark!")
      .foregroundColor(myColor)
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

* 참고

https://developer.apple.com/documentation/swiftui/environmentvalues

https://developer.apple.com/documentation/swiftui/environment

https://developer.apple.com/documentation/swiftui/environmentkey

Comments