Continuing my journey into SwiftUI, I am taking a look at re-using existing UIViews and UIViewControllers in SwiftUI. The primary advantage here is not having to rewrite your existing code from scratch, however, it’s probably best to create any new views in SwiftUI directly rather than UIView.
Let’s start with a simple UIView subclass.
import Foundation
import UIKit
class BinksView: UIView {
}
It doesn’t matter what your view actually does, so I am omitting any specifics. The next step is to simply create a Swift struct that implements UIViewRepresentable like so.
import SwiftUI
import UIKit
struct BinksView: UIViewRepresentable {
func makeUIView(context: Context) -> BinksView {
let control = BinksView()
return control
}
func updateUIView(_ uiView: BinksView, context: Context) {
}
}
That’s it for a UIView subclass!
Let’s look at the case where you have a UIViewController subclass. It’s similar in concept with a few key differences. Keeping on our best Star Wars character ever let’s make a simple UIViewController subclass.
import UIKit
class JarJarViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Just like for UIView, there’s a protocol you can implement to bring this into your SwiftUI app.
struct JarJarViewController: UIViewControllerRepresentable {
var controllers: [UIViewController]
func makeUIViewcontroller(context: Context) -> JarJarViewController {
// you could have a custom constructor here, I'm just keeping it simple
let vc = JarJarViewController()
retrun vc
}
}
These examples are intentionally simple but you can do a lot more custom setup and configuration for your UIView and UIViewController subclasses. I hope this helps get you on the road to SwiftUI Nirvana! Let me know what you think on Twitter and what other SwiftUI content you’d be interested in seeing.