【问题标题】:Check if there is navigation, and present and push from a SwiftUI view检查是否有导航,并从 SwiftUI 视图呈现和推送
【发布时间】:2022-01-22 18:29:05
【问题描述】:

我正在尝试使用 SwiftUI。我已经有一个基于 UIKit 的应用程序正在运行,并且我想集成一个 SwiftUI 视图。我通过使用 UIHostingController 来实现显示这个 SwiftUI 视图。

在这个 SwiftUI 中,我拦截了一个按钮动作。在这个动作中,我想:

  1. 检查是否有导航控制器(它曾经是 UIKit 上的 self.navigationController)
  2. 能够从此 SwiftUI 视图呈现或推送(通过 self.navigationController)新的 UIKit 视图控制器。

我在 SwiftUI 上找不到任何实现这三件事的方法

【问题讨论】:

    标签: ios swift xcode swiftui uikit


    【解决方案1】:

    您可以通过多种方式做到这一点:委托、闭包或者甚至使用组合发布者。我认为最简单的开始方法是使用动作关闭。它可能看起来像这样:

    struct SwiftUIView: View {
        let action: () -> Void
        
        var body: some View {
            Button("press me", action: action)
        }
    }
    
    class ViewController: UIViewController {
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            let swiftUIView = SwiftUIView(action: handleButtonPress)
            
            let hostingController = UIHostingController(rootView: swiftUIView)
            addChild(hostingController)
            
            hostingController.view.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(hostingController.view)
     
            NSLayoutConstraint.activate([
                hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
                hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
                hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
            ])
        }
        
        func handleButtonPress() {
            print("TODO: Insert navigation controller logic here")
        }
    }
    

    【讨论】:

    • 感谢您的回复。我想我认为有比回调和委托更直接的方法来做到这一点。但是,是的,它确实有效。
    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2019-03-28
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多