【问题标题】:How to make a button that dismisses a view presented using UIHostingController/SwiftUI?如何制作一个按钮来关闭使用 UIHostingController/SwiftUI 呈现的视图?
【发布时间】:2020-04-23 02:37:14
【问题描述】:

我有一个相当广泛的项目,我从 UIKit 开始,现在我决定使用 SwiftUI 来制作一些简单的表单页面,但我需要在 SwiftUI 中创建一个按钮来关闭当前视图,该视图显示如下代码:

   func goToSchedule() {
        let vc = UIHostingController(rootView: ScheduleView())
        if let topController = UIApplication.topViewController() {
            topController.present(vc, animated: true, completion: nil)
        }
    }

【问题讨论】:

    标签: swiftui uihostingcontroller


    【解决方案1】:

    您可以通过持有对它的引用来解除它。因此,将vc 保留在更公开的范围内,并在需要时将其关闭。

    var vc: UIViewController
    

    或类似的东西:

    if let topController = UIApplication.topViewController() {
        topController.presentedViewController?.dismiss(animated: true)
    }
    

    【讨论】:

    • 我想使用 SwiftUI 视图中的按钮将其关闭。
    • 没区别,把代码放在一个函数里,在需要的地方调用
    • 谢谢,它有效。出于某种原因,我认为此方法不适用于 SwiftUI,这里唯一的事情是在我的特定情况下它必须是 topController.dismiss(),presentedViewController 返回 nil。
    【解决方案2】:

    如果我正确理解了代码快照,那么.topViewController() 将在显示ScheduleView 时显示为UIHostingViewConroller,所以它应该在里面

    var body: some View {
        // ...
        // somewhere ...
    
        Button("Close") {
            if let topController = UIApplication.topViewController() {
                topController.dismiss(animated: true)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多