我在和SwiftUI玩。目前,我有一个带有故事板的应用程序,只有很少的SwiftUI视图,但有结束视图。
现在,我正在努力从SwiftUI导航到UIKit视图。
NavigationView {
List {
Section(header: Text("App Settings")) {
ForEach(AppSettings.allCases) { item in
NavigationLink(destination: item.navigator) {
SettingsRow(title: item.title, description: item.description, imageName: item.imageName)
}
}.listRowBackground(Color.grayscaleGray3.swiftUIValue)
}
Section(header: Text("Reminders")) {
ForEach(SettingsReminders.allCases) { item in
SettingsRow(title: item.title, description: item.description, imageName: item.imageName)
}.listRowBackground(Color.grayscaleGray3.swiftUIValue)
}
Section(header: Text("About us")) {
ForEach(AboutUs.allCases) { item in
SettingsRow(title: item.title, description: item.description, imageName: item.imageName)
}.listRowBackground(Color.grayscaleGray3.swiftUIValue)
}
.listStyle(GroupedListStyle())
}
}问题出在NavigationLink(目标: item.navigator)...如何导航到这样的UIKit视图?或者有其他方法可以做到这一点?设置将有3-4个部分,在一个部分中有4-6行。有什么帮助吗?
发布于 2021-10-17 15:51:35
你在uikit视图中包装swiftui吗?
就像这样
class ViewController: UIViewController {
private let hostingController = UIHostingController(rootView: SwiftUIView())
override func viewDidLoad() {
addChild(hostingController)
view.addSubview(hostingController.view)
NSLayoutConstraints.activate(your constraint code)
}
}
struct SwiftUIView: View {
var body: some View {
NavigationView {
List {
Section(header: Text("App Settings")) {
ForEach(AppSettings.allCases) { item in
NavigationLink(destination: item.navigator) {
SettingsRow(title: item.title, description: item.description, imageName: item.imageName)
}
}.listRowBackground(Color.grayscaleGray3.swiftUIValue)
}
Section(header: Text("Reminders")) {
ForEach(SettingsReminders.allCases) { item in
SettingsRow(title: item.title, description: item.description, imageName: item.imageName)
}.listRowBackground(Color.grayscaleGray3.swiftUIValue)
}
Section(header: Text("About us")) {
ForEach(AboutUs.allCases) { item in
SettingsRow(title: item.title, description: item.description, imageName: item.imageName)
}.listRowBackground(Color.grayscaleGray3.swiftUIValue)
}
.listStyle(GroupedListStyle())
}
}
}如果您所拥有的内容与上面的代码稍有相似,那么我认为导航不起作用的原因是您使用的是NavigationView,而不是Viewcontroller类的UINavigationController。
在本例中,我要做的是创建一个视图模型,该模型可以从swiftui视图中获取事件并将消息发送到UIViewController
就像这样
struct SwiftUIView: View {
@ObservedObject private let viewModel: MyViewModel
init(vm: MyViewModel) {
self.viewModel = vm
}
enum PresenterEvent {
case navigateToAnotherViewController
}
/* View Code */
}在viewModel中,您可以使用如下所示的函数
class MyViewModel {
func handleSwiftUIViewEvent(_ event: SwiftUIView.PresenterEvent) {
// try to communicate with the view controller based on the event
// then have the view controller to navigate to the desired view controller
}
}我把这些都记在脑海里了,所以如果有什么不清楚的地方或者我漏掉了什么,请告诉我。
https://stackoverflow.com/questions/69591361
复制相似问题