Every now and then I come across an SDK that is not using SwiftUI, but the older UIKit with its UIView and/or UIViewController.

As I am in the process of writing a series on programming DJI drones, I am using DJI’s SDKs which are based on UIKit. Therefore I had to find a way to use them in my app that is based on SwiftUI.

This post explains how to use UIView and UIViewController with SwiftUI apps and provides some “cut-and-paste” ready blueprints.

Feel free to buy me a coffee in case you like this post.

Integrating a UIView

If a UIView-based class is needed in SwiftUI, create a struct that will be the SwiftUI view and implement the UIViewRepresentable protocol.

You provide two methods:

  • makeUIView() and
  • updateUIView()

A Coordinator class can act as a delegate if the UIKit class requires one.

Basically three steps have to be taken to adapt this blueprint:

  1. Change the name MyView to the name of your view.
  2. Change the type SomeUIKitView to the type of the UIView you want to use.
  3. If a delegate is required, remove the comments and replace the delegate type.
struct MyView: UIViewRepresentable {
 
 typealias UIViewType = SomeUIKitView
 
 func makeUIView(context: Context) -> UIViewType {
  let myView = UIViewType()
  // myView.delegate = context.coordinator
  return myView
 }
 
 func updateUIView(_ uiView: UIViewType, context: Context) {
  // left blank
 }
  
 func makeCoordinator() -> MyView.Coordinator {
  return Coordinator(self)
 }
}
 
extension MyView {
 class Coordinator /*: SomeUIKitViewDelegate */ {
  var parent: MyView
   
  init(_ parent: MyView) {
   self.parent = parent
  }
   
  // Implement delegate methods here
 }
}

Integrating a UIViewController

Analogous to UIView, you can integrate a UIViewController by creating a struct that implements UIViewControllerRepresentable. Implement:

  • makeUIViewController and
  • updateUIViewController

Make the same three changes when using this blueprint:

  1. Change the name MyView to the name of your view.
  2. Change the type SomeUIKitViewController to the type of the UIViewController you want to use.
  3. If a delegate is required, remove the comments and replace the delegate type.
struct MyView: UIViewControllerRepresentable {
 
 typealias UIViewControllerType = SomeUIKitViewController
 
 func makeUIViewController(context: Context) -> UIViewControllerType {
  let myViewController = UIViewControllerType()
  // myViewController.delegate = context.coordinator
  return myViewController
 }
 
 func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
  // left blank
 }
  
 func makeCoordinator() -> MyView.Coordinator {
  return Coordinator(self)
 }
}
 
extension MyView {
 class Coordinator /*: SomeUIKitViewDelegate */ {
  var parent: MyView
   
  init(_ parent: MyView) {
   self.parent = parent
  }
   
  // Implement delegate methods here
 }
}

Feel free to buy me a coffee if you liked this post..

Resources