@IBSegueAction 带条件

@IBSegueAction with condition

在我的应用程序中,我想基于 UITapGestureRecognizer 执行转场。如果点击位于屏幕的顶部区域,则应执行到 SettingsView 的 segue。

在 UIKit 中,这非常简单。我通过将它包装在 if 语句中触发了 UITapGestureRecognizer 中的 performSegue。

现在我想在 SwiftUI 中编写 SettingsView()。 SettingsView() 将嵌入到 UIHostingController 中。

我的问题是: 我怎样才能对这个 UIHostingController 执行 segue(同时告诉 UIHostingController 要显示哪个视图)?

我尝试使用新的@IBSegueAction。使用此 @IBSegueAction 的原因是我可以使用它来告诉 UIHostingController 要显示哪个视图。问题是我现在不能插入条件。无论点击在屏幕上的哪个位置,都会执行 segue。我还没有找到取消 @IBSegueAction 中的 segue 的方法。

我的代码目前是这样的:

    @IBSegueAction func showSettingsHostingControler(_ coder: NSCoder, sender: UITapGestureRecognizer, segueIdentifier: String?) -> UIViewController? {

        let location = sender.location(in: self.tableView)
        if let _ = self.tableView.indexPathForRow(at: location) {
            return nil
        } else {
            if location.y < 32 {
                if location.x < view.bounds.midX {
                    direction = .left
                } else {
                    direction = .right
                }
                return UIHostingController(coder: coder, rootView: SettingsView())
            }
        }

        return nil
    }

目前的结果是,当点击错误的区域时,应用会转到一个不存在的 Nil 视图。

based on a UITapGestureRecognizer. In case the tap is in the top area of the screen

我觉得你的点击手势识别器附加到了错误的视图上。这里不应该有任何决定。在屏幕的顶部区域放置一个视图,并将点击手势识别器附加到该视图。这样,如果这个视图被点击,就不需要做出任何决定:点击在正确的位置。