MobileEntityLogo.png

Hi.

Welcome to the best online resource for IOS & Android tutorials.

How to add a UIViewController to your SwiftUI ViewT

How to add a UIViewController to your SwiftUI ViewT

The way this works is we have to wrap our ViewController in something called UIViewControllerRepresentable. It is basically a SwiftUI View that wraps the ViewController in a container. Look at it as a translator from UIKit to SwiftUI. The first thing we need to have is our ViewController all ready to go.

Screen Shot 2020-04-06 at 9.18.00 AM.png

As you can see your ViewController has a label with red text, and a green background. Now lets work on our wrapper.

Screen Shot 2020-04-06 at 9.22.35 AM.png

Our UIViewControllerRepresentable has three required items. The first one is the UIViewControllerType this is where you specify what type of ViewController you want to use, for example PageViewControllers, or TableViewControllers. Next we add the function makeUIViewController which returns the ViewController you wish to use. Keep in mind this can be generated for you if you only specify the UIViewControllerType. Next we have the updateUIViewController method which is where you add any code you want to execute when the view is shown. For example calling a database function to update. Now lets add this wrapper in our SwiftUI View.

Screen Shot 2020-04-06 at 9.30.57 AM.png

Our UIViewControllerRepresentable is of type View so we can’t just plop it in a ZStack, or VStack like you can do with most SwiftUI elements. We have to embed our View using NavigationLink, or any other ways you see fit. Basically anything that takes in a View you can place your wrapper there. This is how our view looks.

Screen Shot 2020-04-06 at 9.35.41 AM.png

In this tutorial we did this in a semi efficient way, however I am working on a framework to do this in a much cleaner way which will be coming soon. Ideally the way we should be able to do this is by calling a SwiftUI element that does not need to be embedded in anything, and pass in the ViewController as a @Binding parameter so that you don’t have to write the wrapper code every time you want to add a ViewController to your SwiftUI View.

How to create UI templates in SwiftUI

How to create UI templates in SwiftUI

How to add placeholders manually to your swift code

How to add placeholders manually to your swift code

0