我是SwiftUI的新手,经过大量研究,当收到通知时,我不知道如何更改tabview选项卡。
当前,我在一个Observable对象中使用@Published var selectedTab
来更改我的tabview选项卡。
它运作很好,但是我的问题是,如果收到通知,我想在特定选项卡中打开该应用程序。
我如何从AppDelegate与我的可观察对象通信以更改selectedTab
值?
非常感谢
在您的Appdelegate类中,导入SwiftUI。
然后推送通知到达,使用此方法显示特定的视图。
extension AppDelegate {
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let vc = ContentView.init()
window?.rootViewController = UIHostingController(rootView:vc)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
}
只需在视图(或模型中,将其定义为默认值)!
import SwiftUI
struct HomeView: View {
let tag: Int
var body: some View {
Text("\(tag) Tab selected").font(.largeTitle)
}
}
struct ContentView: View {
@State var selection = 2
var body: some View {
TabView(selection: $selection) {
HomeView(tag: selection).tabItem {
Image(systemName: "house")
Text("1")
}.tag(1)
HomeView(tag: selection).tabItem {
Image(systemName: "house")
Text("2")
}.tag(2)
HomeView(tag: selection).tabItem {
Image(systemName: "house")
Text("3")
}.tag(3)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
创建后,第二个选项卡被“默认”选中