I'm trying to push a SwiftUI view from UIKit using UIHostingController. In the new view there is a button in the right side of the navigation bar, but it pops after the push animation. I can't make it appear with an animation like in a normal UIViewController.
I tried adding the button in the navigationItem of the hosting controller and in the toolbar of the SwiftUI but none gives a smooth animation.
I've made a small test and this are the results.
This is the code:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Home"
}
@IBAction func buttonNavPressed(_ sender: Any) {
let vc = UIHostingController(rootView: ContentView())
vc.navigationItem.title = "NavItem Button"
vc.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(sayHello))
navigationController?.pushViewController(vc, animated: true)
}
@IBAction func buttonSwiftUIPressed(_ sender: Any) {
let vc = UIHostingController(rootView: ContentViewWithButton())
navigationController?.pushViewController(vc, animated: true)
}
@objc func sayHello() {
print("Hello")
}
}
struct ContentView: View {
var body: some View {
Text("No button")
}
}
struct ContentViewWithButton: View {
var body: some View {
Text("With button")
.navigationTitle("SwuitUI W Button")
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button(action: { print("Hello") },
label: { Image(systemName: "camera") }
)
}
}
}
}
There is any workaround to this problem?