-
[SwiftUI] SwiftUI의 Life cycle👻 iOS 2021. 1. 13. 22:18
SwiftUI를 자주 쓸 계획은 아닌데
하다보니 궁금해서 좀 더 써보고 있습니다.
그런데 막상 시작부터 좀 막히는데
단순히 '컴포넌트의 생명주기는 어디서 구현하지?' 부터 막혔어요
SwiftUI의 modifier 개념은 가이드의 설명으로 봤지만
어떤 modifier 가 있는지는 아직 다 못본 상태거든요.
그런데 이게 chaining 으로 할 수 있는게 생각보다 더 많은것 같아요.
지금 얘기하고자 하는 것들도 이 범위에 포함됩니다.
1. onAppear
apple document : developer.apple.com/documentation/swiftui/text/onappear(perform:)
viewDidAppear 를 대체하는 기능이에요. 어렵지 않네요
2. onDisappear
apple document : developer.apple.com/documentation/swiftui/text/ondisappear(perform:)
viewDidDisappear 를 대체하는 기능이에요. 이것도 쉬워요.
3. onChange
apple document : developer.apple.com/documentation/swiftui/text/onchange(of:perform:)
앱의 foreground 로 올라올 때, background 로 내려갈 때, 그리고 background 상태일 때 3가지 타입의 ScenePhase 환경변수를 이용해서 상태를 감시하고 이용 할 수 있어요.
import SwiftUI struct ContentView: View { @Environment(\.scenePhase) private var scenePhase var body: some View { Text("Life Cycle") .onChange(of: scenePhase) { (phase) in switch phase { case .active: print("active") case .background: print("background") case .inactive: print("inactive") default: print("default") } } } }
4. onOpenUrl
apple document : developer.apple.com/documentation/swiftui/menu/onopenurl(perform:)
커스컴 스킴으로 앱을 띄우고 path를 받아 앱의 특정 화면으로 이동해야 하는 경우에 이 modifier를 사용하네요
간단히 해당 구현을 해주고, info 에 URL Schemes를 셋팅하면 테스트 준비 완료. (여기선 swiftuitest로 스킴을 설정했어요)
import SwiftUI struct ContentView: View { var body: some View { Text("Life Cycle") .onOpenURL(perform: { url in print("url: ", url) }) } }
safari를 열고 주소창에 "swiftuitest://run" 을 입력하면
Xcode console에는 "url: swiftuitest://run" 이 보여지게 됩니다.
공부를 해야할게 많은데 SwiftUI는 음.. 조금 생소해서
실무에서 바로 쓰기가 조금 어려운 느낌이네요.
테스트 하다가 조금 이상한 점을 발견했는데
NavigationView 에서 첫 번째 View의 onDisappear 는 호출이 발생되지 않는 현상이 있어요
진정한 Disappear 가 아니구나 싶다가도 SwiftUI 가 Xcode 버전에 따라 버그가 많다는 얘길 많이 봤는데
이게 버그인지 원래 의도인지 조금 모르겠어서 이건 인지만 해둬야 할 것 같아요.
정리 끝.
git : github.com/maarteti/swiftui-life-cycle
maarteti/swiftui-life-cycle
Contribute to maarteti/swiftui-life-cycle development by creating an account on GitHub.
github.com