简体   繁体   English

检查是否有导航,并从 SwiftUI 视图呈现和推送

[英]Check if there is navigation, and present and push from a SwiftUI view

I am experimenting with SwiftUI.我正在试验 SwiftUI。 I already have a UIKit based app working, and I want to integrate a SwiftUI view.我已经有一个基于 UIKit 的应用程序正在运行,我想集成一个 SwiftUI 视图。 I achieve to show this SwiftUI view by using UIHostingController.我通过使用 UIHostingController 来显示这个 SwiftUI 视图。

In this SwiftUI, I intercept a button action.在这个 SwiftUI 中,我拦截了一个按钮动作。 In this action, I want to:在这个动作中,我想:

  1. Check if there is a navigation controller (what it used to be self.navigationController on UIKit)检查是否有导航 controller(它曾经是 UIKit 上的 self.navigationController)
  2. Be able to present or push (through self.navigationController) a new UIKit view controller from this SwiftUI view.能够从这个 SwiftUI 视图呈现或推送(通过 self.navigationController)一个新的 UIKit 视图 controller。

I cannot find any way to achieve any of these 3 things on SwiftUI我在 SwiftUI 上找不到任何方法来实现这三件事

You could do this multiple ways: delegates, closures or heck even with combine publishers.你可以通过多种方式做到这一点:委托、闭包或者甚至使用组合发布者。 The easiest way to get started is with an action closure I think.我认为最简单的开始方法是使用动作关闭。 It could look something like this:它可能看起来像这样:

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")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM