iOS/SwiftUI

Swift 에서 observable, event와 state

태애니 2025. 4. 4. 17:43
728x90

Scrumdinger 를 만들면서 나온 설명들을 정리<< 

 

https://developer.apple.com/tutorials/app-dev-training/making-classes-observable

 

Making classes observable | Apple Developer Documentation

You’ve used the and property wrappers to define a value type as a source of truth for triggering updates in your view hierarchy. In this article, you’ll learn how to define a reference type as a source of truth for your app’s user interface.

developer.apple.com

https://developer.apple.com/tutorials/app-dev-training/responding-to-events

 

 

 

 

Making classes observable 

used the @State and @Binding property wrappers to define a value type as a source of truth for triggering updates in your view hierarchy.

State, Bindable, or Environment.

 

@State and @Binding property wrappers to define a value type as a source of truth for triggering updates in your view hierarchy. 

 

 

 

 

 

Use the @Environment property wrapper to share an observable object in a complex view hierarchy.

 

 

 

@Environment 속성 래퍼를 사용하여 복잡한 계층 구조에서 ObservableObject 공유할 있습니다. 객체를 이니셜라이저를 통해 전달하는 대신, 환경(environment) 객체를 배치할 있습니다.

 

 

Responding to events 

 

 

Scene architecture 

 

Scene 은 system life cycle 을 관리하는 user interface 의 일부이다.

 

App 프로토콜을 따르는 구조체를 정의해야하는데,

@main 속성을 이용하여 시스템에 해당 구조체가 유인한 진입점임을 표시한다.

App 구조체의 body 속성 안에서 Scene 프로토콜을 따르는 하나의 씬을 추가하여 뷰 계층 구조의 컨테이너 역할을 한다.

iOS, watchOS 의 경우 하나의 씬, macOS 와 iPadOS 의 경우 여러개의 씬을 표시하도록 디자인이 가능하다.

 

 

 

 

 

 

 

 

 

WindowGroup 과 같이 구체적인 씬을 제공한다.

iPadOS에서 멀티태스킹을 사용할 경우 같은 앱의 여러 개의 작은 인스턴스를 동시에 표시할 수 있다.

 

 

 

Scene phases and transitions 

씬의 세가지 phase

 

active : scene - foreground

inactive : system disabled interaction with the scene. (예시로 멀티태스킹 모드에서 다른앱과 함께 표시 중이지만 현재 active 된 패널이 아님)

background:scene isn’t visible in the user interface. A scene enters this phase prior to app termination. 

 

 

 

이 Scene 의 상태값에 관련된 값을 얻으려면

scenePhase 환경 값을 사용할 수 있다.

 

이 부분은 추가로 포스팅해보겠음.

 

 

 

 

Events and state

사용자의 event 또는 앱 state 변화에 따른 SwiftUI 반응


기존의 경우(imperative) 명령형 패턴에서는 프로그램 상태 변화에 따라 직접 뷰를 변경해야하지만

SwiftUI 는 선언형(declarative) 패턴을 따른다.

 

모든 상태에 대해 User Interface 가 어떻게 나타나는지 선언 하면, UI를 동기화 해서 그 부분만 업데이트 한다. -> 뷰를 조각조각 내야 성능을 더 잘내는 이유가 이 때문

 

 

사용자 상호작용 또는 알림(notification) 과 같은 이벤트가 발생하면 알아서 앱이 반응하는데,

 A closure runs in response to the event, which might result in a mutation in the source of truth. After observing a mutation, 

SwiftUI updates the view and renders the user interface. -> SwiftUI 가 알아서 렌더링 해준다.

 

 

 

 

View life cycle events 

 

View 가 appear 하거나 disappear 하는 상황에서도 앱 상태를 변경해야할 경우가 있다.

이를 감지하는 modifier 를 활용하면 된다. -> 이것도 포스팅으로 다뤄보겠음

 

 

  • onAppear(perform:) triggers actions any time the view appears on screen, even if it’s not the first time.
  • onDisappear(perform:) triggers actions when a view disappears from screen.

 

 

 

 

 

 

728x90