首页 > 解决方案 > 从故事板返回主机控制器到另一个控制器

问题描述

我有一个项目,Storyboard但现在我正在迁移到SwiftUI.

我有一个Hosting Controller控制 del SwiftUI 段,但现在我需要从它返回到另一个控制器Storyboard

基本上我可以这样做:Storyboard (Controller 1)-> HostingController (SwiftUI)。所以现在我需要返回:HostingController (SwiftUI)-> Storyboard (Controller 2)

标签: swiftswiftuiuikitstoryboard

解决方案


我喜欢为此使用闭包。我假设您正在展示这样的主机控制器?

let viewController = UIHostingController(rootView: ContentView())
self.present(viewController, animated: true)

dismissSelf您可以在 SwiftUI View 结构中添加一个闭包:

struct ContentView: View {
    var dismissSelf: (() -> Void)?
    
    var body: some View {
        Button(action: {
            dismissSelf?()
        }) {
            Text("Return")
        }
    }
}

这将dismissSelf在按下按钮时调用。现在,您需要分配dismissSelf一个代码块来消除UIHostingController. 你可以这样做:

class ViewController: UIViewController {    
    @objc func buttonPressed() {
        
        var viewController: UIViewController?
        
        let contentView = ContentView {
            /// set the closure (it's a trailing closure, so you don't need to put the `dismissSelf`)
            viewController?.dismiss(animated: true, completion: nil)
        }
        
        viewController = UIHostingController(rootView: contentView)
        
        if let vc = viewController {
            self.present(vc, animated: true, completion: nil)
        }
    }

    /// make the button
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(frame: CGRect(x: 50, y: 50, width: 80, height: 40))
        button.setTitle("Present", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
        
        view.addSubview(button)
    }
}

有一件事有点奇怪viewController永远不会为零,但为了避免强制展开,我放入了if let.

结果:

呈现按钮以呈现 SwiftUI 视图,其中包含一个返回按钮以返回主屏幕

推荐阅读