Search

변수가 변할 때 >> 반응형으로 뷰가 애니메이션 하게 만드는법 - onChange method

부제
카테고리
SwiftUI
세부 카테고리
애니메이션
Combine 카테고리
최종편집일
2022/07/16 15:58
작성중
관련된 포스팅
생성 일시
2022/07/16 15:58
태그

onChange method

Adds a modifier for this view that fires an action when a specific value changes.
특정 값이 변경되었을 때 view 에 action 을 트리거한다.

Declaration

func onChange<V>(of value: V, perform action: @escaping (V) -> Void) -> some View where V : Equatable
Swift
복사

Return Value

A view that fires an action when the specified value changes.

Parameters

value The value to check against when determining whether to run the closure.
감시할 밸류를 넣어준다
action A closure to run when the value changes.
감시하는 밸류가 변경되면 취할 액션을 클로져로 넣어준다.
newValue The new value that failed the comparison check.

Discussion

You can use onChange to trigger a side effect as the result of a value changing, such as an Environment key or a Binding.
onChange is called on the main thread. Avoid performing long-running tasks on the main thread. If you need to perform a long-running task in response to value changing, you should dispatch to a background queue.
The new value is passed into the closure. The previous value may be captured by the closure to compare it to the new value. For example, in the following code example, PlayerView passes both the old and new values to the model.
struct PlayerView : View { var episode: Episode @State private var playState: PlayState = .paused var body: some View { VStack { Text(episode.title) Text(episode.showTitle) PlayButton(playState: $playState) } .onChange(of: playState) { [playState] newState in model.playStateDidChange(from: playState, to: newState) } } }
Swift
복사