Swift/Swift 개발 노트

[iOS/Swift] updateUIView 가 실행되지 않아요.

힛해 2024. 8. 20. 00:55
728x90

updateUIView란?

SwiftUI의 새로운 정보로 지정된 뷰의 상태를 업데이트 하는 메서드로,

UIViewRepresentable 프로토콜 필수 구현 함수로 화면이 SwiftUI에서 불러지고있는 UIView에서 변경이 일어났을떄 호출되는 함수다!

 

 

예시코드

struct ContentView: View {
    
    @State var showChic = false
    var body: some View {
        VStack{
            Text("3D Test")
            
            DolView(showChic: $showChic)
            Button("Show Chic") {
                // 일단 showChic를 false로 설정하여 상태 변화를 유도
                showChic.toggle()
                    print("뷰 토글 : ", showChic)
                        }
        }.background(Color.green)
        
    }
}

struct DolView : UIViewRepresentable {
    @Binding var showChic: Bool
    
    
    // UI가 만들어질때 생성
    func makeUIView(context: Context) -> SCNView {
        let scnView = SCNView()
        scnView.scene = loadScene()
        scnView.backgroundColor = UIColor.clear // SCNView의 배경을 투명하게 설정
        scnView.allowsCameraControl = true
        
        return scnView
    }
    
    func updateUIView(_ uiView: SCNView, context: Context) {
    print("업데이트")
    }
....

 

이렇게 구현되어있다면 ContentView 에서 변경이 일어난다면 updateUIView 함수가 실행될 것이다.

 

그러나 결과는 아래와 같다.

업데이트
뷰 토글 :  true
뷰 토글 :  false
뷰 토글 :  true
뷰 토글 :  false
뷰 토글 :  true

 

버튼을 아무리 눌러도 updateUIView 함수는 View 생성시에만 호출이 되고 재호출 되지 않는다.

 

어째서일까?

 

상태값이 변화했지 그로인한 UIView가 변화하지 않았기 떄문이다.

 

 

그럼 아래와 같이 만들어보자

 

struct ContentView: View {
    
    @State var showChic = false
    var body: some View {
        VStack{
            Text("3D Test")
            
            DolView(showChic: $showChic)
            Button("Show Chic") {
                // 일단 showChic를 false로 설정하여 상태 변화를 유도
                showChic.toggle()
                    print("뷰 토글 : ", showChic)
                        }
            Text("\(showChic)")
        }.background(Color.green)
        
    }
}

struct DolView : UIViewRepresentable {
    @Binding var showChic: Bool
    
    
    // UI가 만들어질때 생성
    func makeUIView(context: Context) -> SCNView {
        let scnView = SCNView()
        scnView.scene = loadScene()
        scnView.backgroundColor = UIColor.clear // SCNView의 배경을 투명하게 설정
        scnView.allowsCameraControl = true
        
        return scnView
    }
    
    func updateUIView(_ uiView: SCNView, context: Context) {
    print("업데이트")
    }

 

상태값을 toggle 했을때 Text로서 보여주기때문애 버튼을 반복해서 누르면 함수가 계속 실행이 된다.

 

실행 결과

업데이트
뷰 토글 :  false
업데이트
뷰 토글 :  true
업데이트
뷰 토글 :  false
업데이트
뷰 토글 :  true
업데이트
뷰 토글 :  false
업데이트

 

정리하자면

updateUIView 함수는 상태값을 추적하는 것이 아닌 상태값으로 인해 UI가 변경되었을떄 실행되는 효율적인 구현이 가능한 메서드이다!