본문 바로가기

iOS/SwiftUI

[SwiftUI] SwiftUI View를 UIView로 변환하기 (UIHostingController)

UIKit의 요소를 SwiftUI View에 통합시켜주기 위해 UIViewRepresentable UIViewControllerRepresentable 을 사용한다면, 반대로 SwiftUI ViewUIView로 변환하기 위해서는 UIHostingController 를 사용합니다

 

struct InfoWindowView: View {
        
    var name: String
    var address: String?

    var body: some View {
        VStack(spacing: 0) {
            VStack(alignment: .leading, spacing: 0) {
                Text(name)
                    .font(.custom("NotoSansCJKkr-Bold", size: 13))
                    .foregroundColor(Color(red: 0.12156862745098039, green: 0.12156862745098039, blue: 0.12156862745098039))
                Text(address ?? "")
                    .font(.custom("NotoSansCJKkr-Regular", size: 13))
                    .foregroundColor(Color(red: 0.6588235294117647, green: 0.6588235294117647, blue: 0.6588235294117647))
                    .lineLimit(1)
            } //VStack
            .padding(.top, 10)
            .padding(.bottom, 17)
            .padding(.horizontal, 17)
            .background(
                AddressBubble()
            )
            .padding(.bottom, 5)

            Image("ic_position_marker")
        }
    }
}

UIView로 변환하기 위한 View를 작성해보았습니다.

네이버 지도에 보여주기위한 View로, 왜 이런 변환 과정을 거치는지는 다음에 포스팅해보겠습니다.

 

let controller = UIHostingController(rootView: infoWindowView)
controller.view.frame = CGRect(origin: .zero, size: CGSize(width: 240, height: 110))
controller.view.backgroundColor = .clear

if let rootVC = UIApplication.shared.windows.first?.rootViewController {
    rootVC.view.insertSubview(controller.view, at: 0)
}

일반적인 UIView와 똑같이, 변환한 UIView의 크기도 직접 frame을 정해주거나 autolayout을 적용할 수 있습니다.