如何使用主页快速操作打开特定视图

How to open to a specific view using home quick actions

我是 Swift 的新手,一直在使用 SwiftUI,而不是 Storyboard。

我在 Info.plist 中设置了 UIApplicationShortcutItems,并且有两个快速操作可以通过 launchOptions 显示警报。

我可以切换大小写 SceneDelegate.swift

中的快速操作
func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    switch shortcutItem.type {
    case "QuickAction1":
        OneView() // What do I do to open this SwiftUI struct View?
        break
    case "QuickAction2":
        SecondView() // What do I do to open this SwiftUI struct View?
        break
    default:
        break
    }
}

使用 SwiftUI 从主页快速操作打开特定视图的正确方法是什么?


ContentView.swift

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: OneView())
                NavigationLink(destination: TwoView())
            }
        }
    }
}

这是可能的步骤方法(使用 Xcode 11.2 / iOS 13.2 测试)

  1. 添加 AppSettings class 以存储要通过快捷方式呈现的视图模式
    class AppSettings: ObservableObject {
        enum Mode {
            case one
            case two
        }
        @Published var mode: Mode? = nil
    }
  1. 使 appSettings 场景委托成员访问它并在 ContentView 和快捷方式委托中将其作为环境对象传递给 ContentView
    let appSettings = AppSettings()
    
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
        let contentView = ContentView().environmentObject(appSettings)
        // ...
  1. 在快捷场景委托中激活相应模式
    func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        switch shortcutItem.type {
        case "QuickAction1":
            appSettings.mode = .one
            break
        case "QuickAction2":
            appSettings.mode = .two
            break
        default:
            break
        }
        // ...
    }
  1. 根据选择的快捷模式ContentView有条件地显示链接
    struct ContentView: View {
        @EnvironmentObject var appSettings: AppSettings
        
        var body: some View {
            NavigationView {
                VStack {
                    NavigationLink(destination: OneView(),
                                   tag: AppSettings.Mode.one,
                                   selection: $appSettings.mode)
                        { Text("To One") }
                    NavigationLink(destination: TwoView(),
                                    tag: AppSettings.Mode.two,
                                    selection: $appSettings.mode)
                        { Text("To Two") }
                }
            }
        }
    }

backup