SwiftUI and its Incorporation in UIKit Project

Tania Jasam
Pepperfry Tech
Published in
2 min readSep 4, 2021

Apple introduced a new framework “SwiftUI” that is an advanced way of declaring user interfaces for apps across all platforms. It not only enhances the app with better features and performance, but also makes the maintenance easy. SwiftUI uses declarative syntax, which makes the code simpler and easily understandable.

Apple introduced SwiftUI

No more merge conflicts in Storyboards/XIBs

SwiftUI is a modern way of building apps that has eliminated Storyboards and Auto Layout. Instead with SwiftUI, we have code editor and preview canvas saving our time from running the app and again for creating UI. Now you just have to write code in the code editor and Xcode renders the user interface in real time and displays it on the canvas. This completely removes the possibility of merge conflicts in Storyboards/XIBs (trickiest conflicts to resolve).

Phewww!!!!

Easy animations in SwiftUI

Declarative way of SwiftUI allows us to deal with complex animations very easily. With few lines of code, we can add animation to any view or view’s state with ready to use tools. System itself manages to maintain smooth and uninterrupted animations.

Easy Animations with SwiftUI

Incorporating SwiftUI Views in a project using UIKit

So we agree that SwiftUI is cool, manageable, provides fancy animations, removes the possibility of conflicts, and eventually makes our lives easy. But how can we use it with our existing project that is using UIKit (of course you are not going to write all the views from scratch). So Apple kept the backward compatibility in mind, and there’s a way for this — UIHostingViewController. We need to add a UIHostingViewController which will embed SwiftUI content view in it.Make sure that the SwiftUI view which you embed in UIHostingViewController, contains all the sub views. In other words, you would be adding a single SwiftUI view to hosting controller, which would be having other SwiftUI views (if any), as sub views.

Adding SwiftUI view in UIViewController

We should not hesitate in using SwiftUI. Though it is not completely evolved as UIKit but it has workarounds for everything. Apple is continuously trying to improve it- with iOS 15 most of the glitches have been fixed and new features have been introduced.

Let’s start using it from today itself!! 🙂

--

--

Tania Jasam
Pepperfry Tech

Senior Software Engineer @Pepperfry | Ex-Hungama, Jio | NITJ