微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 SwiftUI 推送到 UIViewController

如何解决从 SwiftUI 推送到 UIViewController

我的应用是 UIKitSwiftUI 的混合体。我有一个用例,用户可能需要点击 Button 中的 SwiftUI.View,但推送到 UIViewController 或另一个 UIHostingController

我的项目使用 Storyboard

我正在使用 UINavigationControllerUITabBarController

我正在考虑两种情况。

1.) 从我在主屏幕上的初始启动开始,我可以点击一个按钮并在其操作中:

let vc = UIHostingController(rootView: RootView())
self.navigationController?.pushViewController(vc,animated: true)

这按预期工作。

2.) 我点击了一个不同的选项卡,它认为我的 SwiftUI RootView,它托管在我在 UIHostingController 中使用的自定义 Storyboard 中。在这里,如果我点击一个按钮来触发推送,它不会推送。我只看到 View 我正在更新。

我也在使用自定义 UINavigationController。从我的 Storyboard 中,标签关系转到自定义 UINavigationController,然后它的根是适当的 UIViewController。在一种情况下,虽然它是我的自定义 UIHostingController,因此我可以最初从选项卡选择加载 SwiftUI 视图。

这是我尝试从 SwiftUI 视图处理推送到视图控制器的操作:

final class AppData: ObservableObject {
    weak var window: UIWindow? // Will be nil in SwiftUI previewers

    init(window: UIWindow? = nil) {
        self.window = window
    }
    
    public func pushViewController(_ viewController: UIViewController,animated: Bool = true) {
        let nvc = window?.rootViewController?.children.first?.children.first as? UINavigationController
        nvc?.pushViewController(viewController,animated: animated)
    }
}

// This is what is triggered from the Button action.
func optionSelected(option: String) {
    if let optionId = Common.getIDByOption(option: option) {
        let vc = UIHostingController(rootView: RootView())                
        appData.pushViewController(vc,animated: true)
    }
}

发生了什么:

  • 我确实看到数据发生了变化,但它们都在我已经使用的同一个视图中。
  • 我需要推送到新的 UIHostingController

解决方法

如果您以 sub(/^>/,"") { hdr = $0 next } { while ( match($0,/GC[AT]GC/) ) { print hdr,RSTART,substr($0,RLENGTH) $0 = substr($0,1,RSTART-1) " " substr($0,RSTART+1) } } UIKit 处理导航的方式混合 SwiftUIUITabBarController。我建议你剪掉UINavigationControllerNavigationView。背后的原因很简单。 NavigationLink 将在每次切换到选项卡时重新创建。因此,您将从头开始。您可以四处走动,但在这种情况下,使用 SwiftUI.View 会更容易。

假设您的应用有两个标签。我会把 UINavigationController 放在 SwiftUI.View 中,然后放在 UIHostingController 中。在 UINavigationController 中,我会放置闭包 SwiftUI.View,每当您需要将下一个 let onTap: () -> VoidUIHostingController 推送到 UIViewController 时都会调用它。

示例

UINavigationController

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。