[英]How to push to a UIKit ViewController with back button from a SwiftUI View
I've added a SwiftUI View
to an existing UIKit/Storyboard project.我已将 SwiftUI View
添加到现有的 UIKit/Storyboard 项目中。 The SwiftUI View
is embedded in a UIHostingController
. SwiftUI View
嵌入在UIHostingController
。 However, I now want to push to an existing UIViewController
so that I have a back button and navigation bar.但是,我现在想推送到现有的UIViewController
以便我有一个后退按钮和导航栏。 The code below obviously just presents the UIViewController
modally, how can I do this?下面的代码显然只是以模态方式呈现UIViewController
,我该怎么做?
class DashBoardHostingController: UIHostingController<DashboardView> {
required init?(coder: NSCoder) {
super.init(coder: coder, rootView: DashboardView())
}
}
struct DashboardView: View {
var body: some View {
ScrollView {
VStack(alignment: .leading) {
HStack {
Text("Workouts")
.font(.title)
.fontWeight(.bold)
.padding(.leading)
Spacer()
Button(action: {
let storyBoard: UIStoryboard = UIStoryboard(name: "Version3", bundle: nil)
let subscribeViewController = storyBoard.instantiateViewController(withIdentifier: "skateListVC") as! SkateListTableViewController
UIApplication.topViewController()?.present(subscribeViewController, animated: true, completion: nil)
}) {
Text("Show More")
}
.padding(.trailing)
}
ZStack {
VStack(alignment: .leading) {
WorkoutListView(workouts: [MockWorkout().getMockWorkout()])
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(20)
.background(Color.white)
.cornerRadius(10)
.padding()
}
}
}
Without going and trying this myself, I would think that your SwiftUI view needs to be within a navigationView so that there is a navigation controller to be pushed onto.如果我自己不去尝试这个,我会认为你的 SwiftUI 视图需要在一个 navigationView 中,以便有一个导航控制器被推到上面。 If UIHostingController
provides a navigation controller on its own then you should be able to just change UIApplication.topViewController()?.present(subscribeViewController, animated: true, completion: nil)
to UIApplication.topViewController()?.navigationController.pushViewController(subscribeViewController, animated: true)
如果UIHostingController
自己提供导航控制器,那么您应该能够将UIApplication.topViewController()?.present(subscribeViewController, animated: true, completion: nil)
更改为UIApplication.topViewController()?.navigationController.pushViewController(subscribeViewController, animated: true)
Either way, you will need to make sure that there is a navigation controller which can be pushed onto.无论哪种方式,您都需要确保有一个可以推送到的导航控制器。
I think the better way to do this actually would be to wrap the old UIKit vc in a UIViewControllerRepresentable
and it can be treated like a normal swiftui view.我认为更好的方法实际上是将旧的 UIKit vc 包装在UIViewControllerRepresentable
,并且可以将其视为普通的 swiftui 视图。 A great tutorial can be found here Interfacing with UIKit一个很棒的教程可以在这里找到UIKit 接口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.