swift - 如何使用主页快速操作打开特定 View

标签 swift swiftui quickaction

我是 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 从家庭快速操作打开特定 View 的正确方法是什么?

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

最佳答案

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

1) 添加AppSettings存储由快捷方式呈现的 View 模式的类

class AppSettings: ObservableObject {
    enum Mode {
        case one
        case two
    }
    @Published var mode: Mode? = nil
}

2) 制作 appSettings场景代表成员访问它并在 ContentView并在快捷方式委托(delegate)中传递 ContentView作为环境对象
let appSettings = AppSettings()

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    let contentView = ContentView().environmentObject(appSettings)
    // ...

3)在快捷场景委托(delegate)中激活相应模式
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
    }
}

4) 制作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") }
            }
        }
    }
}

关于swift - 如何使用主页快速操作打开特定 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59677445/

相关文章:

ios - SwiftUI 将 VStack/HStacks 对齐到一个表中

ios - Swift UI 相机显示纵向 View ,但图像变成横向 View

ios - 在创建的路径顶部添加形状

ios - 覆盖静态 UIApplicationShortcutItems

安卓 : Get view Reference to a Menu Item

arrays - 如何将数据插入到空数组的文本字段中,然后显示在标签中?

swift - 如何将 Pod 添加到 Swift 包中

ios - 按键中对象的属性对字典进行排序/过滤

ios - swift : TableView Cells not getting selected correctly

android - 获取 map 的标记作为 View