Skip to content

Latest commit

 

History

History
59 lines (36 loc) · 1.93 KB

20230518.md

File metadata and controls

59 lines (36 loc) · 1.93 KB

Today I Learn

  • Date: 2023/5/18

SwiftUI에 UIKit view, viewController 통합

  • UIKit Project ← SwiftUI View
  • SwiftUI Project ← UIKit View/ViewController

Adding UIKit views to SwiftUI view hierachies

  • protocol UIViewRepresentable

    • A wrapper for a UIKit view that you use to integrate that view into your SwiftUI view hierarchy.
  • struct UIViewRepresentableContext

    • Contextual information about the state of the system that you use to create and update your UIKit view.
  • protocol UIViewControllerRepresentable

    • A view that represents a UIKit view controller.
  • struct UIViewControllerRepresentableContext

    • Contextual information about the state of the system that you use to create and update your UIKit view controller.

UIKit VC를 SwiftUI 프로젝트에 사용할 때

  • UIKit에서 만든 VC를 SwiftUI에서 만든 프로젝트에서 사용할 경우 아래와 같은 방법으로 하면 손쉽게 사용가능하다.
  • UIViewControllerRepresentable을 채택하게 만들고
  • func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { }
  • func makeUIViewController(context: Context) -> some UIViewController을 구현한다.
  • func getRepresentable() -> some View를 VC에서 호출하면 SwiftUI에서 사용가능하다.
// MARK: - ViewController Representable

extension MainViewController {
  private struct ViewControllerRepresentable: UIViewControllerRepresentable {
    let mainViewController: MainViewController
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { }
    
    func makeUIViewController(context: Context) -> some UIViewController {
      mainViewController
    }
    
  }
  
  func getRepresentable() -> some View {
    ViewControllerRepresentable(mainViewController: self)
  }
}

출처( Apple Developer Document : 링크)