SwiftUI View life cycle

Jungin Yoo·2022년 8월 2일
post-thumbnail

View life cycle

1. onAppear()

func onAppear(perform action (() -> Void)? = nil) -> some View
  • return값으로 view가 나타날 때 action을 트리거한 view를 반환
  • view가 나타날 때 action 수행
  • perform에 들어가는 action값은 optional
  • action이 nil인 경우 아무런 effect가 없음
func onAppear()
func onAppear(perform: {
	// action
})

2. onDisappear()

func onDisappear(perform action: (() -> Void)? = nil) -> some View
  • onAppear()과 유사하게 사용
  • view가 사라질 때 action 수행

3. onChange()

func onChange<V> {
	of value: V,
    perform action: @escaping (V) -> Void
} -> some View where V : Equatable
  • 특정 값이 변할 때 action 수행한다.

  • onChange 메서드 파라미터

    • value: 클로저 실행 여부를 결정할 때 확인할 값
    • action: 값이 변경될 때 실행할 클로저
    • newValue: 비교 검사에 실패한 새로운 값
  • onChange를 사용해 Environment key 또는 Binding과 같은 값 변경의 결과로 side-effect를 트리거할 수 있다.

  • onChange는 메인 스레드에서 호출된다.

    • 메인 스레드에서 긴 작업은 피해야 된다.
    • 값 변경의 결과로 긴 작업을 수행해야 한다면 백그라운드 큐로 dispatch해야 된다.
  • newValue는 closure로 전달된다.

    • closure가 이전 값을 캡처하여 새 값과 비교할 수 있다.

Resources

https://developer.apple.com/documentation/swiftui/view/onappear(perform:)
https://developer.apple.com/documentation/swiftui/view/ondisappear(perform:)
https://developer.apple.com/documentation/swiftui/view/onchange(of:perform:)

profile
Junior iOS Developer

0개의 댓글