【问题标题】:Wrapped SwiftUI View popping itself包装的 SwiftUI 视图自行弹出
【发布时间】:2021-07-22 21:30:57
【问题描述】:

我有一个包装在 UIHostingController 中的 SwiftUI 视图,然后从 UIViewController 推送到导航堆栈。

是这样推送的:

let controller = TransactionDetailsHostingController(transactionRecord: record)
navigationController?.pushViewController(controller, animated: true)

我想要一个自定义的后退按钮,它可以从导航堆栈中弹出视图,我尝试了这里和其他地方使用的技术:SwiftUI - Is there a popViewController equivalent in SwiftUI?

不幸的是,它不起作用。包装的视图不会从导航堆栈中弹出。我需要一个适用于 iOS 13 的解决方案。

【问题讨论】:

    标签: swiftui uinavigationcontroller


    【解决方案1】:

    pop查看控制器有两种方式。

    1. 使用闭包。在 SwiftUI 视图中创建闭包并从控制器调用。 这是演示。
    struct SwiftUIView: View {
        var onBack: () -> Void
        
        var body: some View {
            Button(action: {
                onBack()
            }, label: {
                Text("Go to back")
            })
        }
    }
    
    class ViewController: UIViewController {
        
        @IBAction func onNavigation(_ sender: UIButton) {
            let controller = UIHostingController(rootView: SwiftUIView(onBack: {
                self.navigationController?.popViewController(animated: true)
            }))
            navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    

    1. 找到最上面的控制器并弹出。您可以从here 找到顶级控制器

    然后像这样使用

    UIApplication.shared.topMostViewController()?.navigationController?.popViewController(animated: true)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多