Is is possible to build views with SwiftUI side by side with an existing UIKit application?
I have an existing application written in Objective-C. I've begun migrating to Swift 5. I'm wondering if I can use SwiftUI alongside my existing UIKit .xib views.
That is to say I want some views built with SwiftUI and some other views built with UIKit in the same app. Not mixing the two of course.
SomeObjCSwiftProject/
SwiftUIViewController.swift
SwiftUIView.xib
UIKitViewController.swift
UIKitView.xib
Working alongside each other
Others has been showcasing how to use UIHostingController.
I can show how you can present a UIViewController from SwiftUI UIViewControllerRepresentable:
If you're looking to create a SwiftIU view from a legacy Objective C project, then this technique worked perfectly for me,
See Adding SwiftUI to Objective-C Apps
Kudos to our friend who wrote that up.
One item I have not seen mentioned yet, and involves Xcode 11 beta 5 (11M382q) involves updating your app's info.plist file.
For my scenario, I am taking an existing Swift & UIKit based application and fully migrating it to be an iOS 13 & pure SwiftUI app, so backwards compatibility is not a concern for me.
After making the necessary changes to AppDelegate:
And adding in a SceneDelegate class:
I was encountering a problem where my SceneDelegate was not being called. This was fixed by adding the following into my info.plist file:
And a screenshot to see:
The main items to keep in sync are:
SceneDelegate
fileUISceneConfiguration
After doing this, I was then able to load my newly created HomeList view (A SwiftUI object)
UIHostingController
Although at the moment the documentation for the class has not been written,
UIHostingController<Content>
seems to be what you're looking for: https://developer.apple.com/documentation/swiftui/uihostingcontrollerI've just tried it in my app with the following line of code:
Where
BenefitsSwiftUIView
is just the default "Hello World"View
fromSwiftUI
. This works exactly as you expect it. It also works if you subclassUIHostingController
.edit 05/06/19: Added information about UIHostingController as suggested by @Departamento B in his answer. Credits go to him!
Using SwiftUI with UIKit
One can use
SwiftUI
components in existingUIKit
environments by wrapping aSwiftUI
View
into aUIHostingController
like this:It's also possible to override
UIHostingController
and customize it to one's needs, e. g. by setting thepreferredStatusBarStyle
manually if it doesn't work viaSwiftUI
as expected.UIHostingController
is documented here.Using UIKit with SwiftUI
If an existing
UIKit
view should be used in aSwiftUI
environment, theUIViewRepresentable
protocol is there to help! It is documented here and can be seen in action in this official Apple tutorial.Compatibility
Please note that
UIKit
andSwiftUI
components can only be used in conjunction if the app targets iOS 13+, asSwiftUI
is only available iOS 13+. See this post for more information.