如何使用主页快速操作打开特定视图 [英] How to open to a specific view using home quick actions
问题描述
我是 Swift 的新手,一直在使用 SwiftUI,而不是 Storyboard.
I am new to Swift and have been using SwiftUI, not Storyboard.
我在 Info.plist 中设置了 UIApplicationShortcutItems,并有两个快速操作可以通过 launchOptions 显示警报.
I set the UIApplicationShortcutItems in the Info.plist and have two quick actions that are able to present an alert with launchOptions.
我可以在 SceneDelegate.swift 中切换快速操作
I am able to switch-case out the quick actions in 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 从主页快速操作打开特定视图的正确方法是什么?
What is the proper way to open a particular view from a home quick action using SwiftUI?
ContentView.swift
ContentView.swift
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: OneView())
NavigationLink(destination: TwoView())
}
}
}
}
推荐答案
以下是可能的方法(使用 Xcode 11.2/iOS 13.2 测试)
Here is possible approach by steps (tested with Xcode 11.2 / iOS 13.2)
1) 添加AppSettings
类来存储快捷方式呈现的视图模式
1) Add AppSettings
class to store mode of views to be presented by shorcut
class AppSettings: ObservableObject {
enum Mode {
case one
case two
}
@Published var mode: Mode? = nil
}
2) 让 appSettings
场景委托成员访问它,并在 ContentView
和快捷方式委托中将其作为环境对象传递到 ContentView
中
2) make appSettings
scene delegate member to access it and in ContentView
and in shortcut delegate and pass it in ContentView
as environment object
let appSettings = AppSettings()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let contentView = ContentView().environmentObject(appSettings)
// ...
3) 在快捷场景委托中激活相应的模式
3) activate corresponding mode in shortcut scene 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
根据选择的快捷方式有条件地呈现链接
4) Make ContentView
present links conditionally based on selected shortcut mode
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") }
}
}
}
}
这篇关于如何使用主页快速操作打开特定视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!