SwiftUI 프로젝트에 UIKit 뷰를 추가하려면 UIViewControllerRepresentable
프로토콜을 사용하면 된다.
makeUIView(context:)
SwiftUI가 UIView 인스턴스를 생성할 때 호출, UILabel을 생성하는 등 초기 설정을 한다.
updateUIView(_:context:)
SwiftUI가 UIView의 상태를 업데이트할 때 호출, UILabel의 텍스트를 업데이트한다.
import SwiftUI
import UIKit
struct LabelView: UIViewRepresentable {
var text: String
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
label.text = text
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 24)
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
}
}
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("This is a SwiftUI Text")
.font(.headline)
.padding()
LabelView(text: "This is a UIKit UILabel")
.frame(height: 50)
.padding()
Spacer()
}
}
}
extension MainVC {
private struct VCRepresentable : UIViewControllerRepresentable {
let mainVC : MainVC
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
func makeUIViewController(context: Context) -> some UIViewController {
return mainVC
}
}
func getRepresentable() -> some View {
VCRepresentable(mainVC: self)
}
}
struct ContentView: View {
var body: some View {
MainVC().getRepresentable()
}
}