如何使用没有任何页面转换或任何重启应用程序的方法 [英] How can I use a method without any page transition or any reboot app

查看:27
本文介绍了如何使用没有任何页面转换或任何重启应用程序的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 SwiftUI 开发应用程序.

我想在视图出现时使用一个方法.

对于我在下面附加的代码,我可以在应用启动时使用 print 方法并在页面之间进行一些转换.


但是当我重新打开应用程序时,我想使用 print 方法,如下所示:

  • 1:在模拟器上运行代码(我可以看到 print 方法有效).

  • 2:按下主页按钮.

  • 3:点击应用程序图标打开应用程序(我看不到 print 方法有效).

    (*) 我想在这里使用 print 方法.

在这种情况下,我怎样才能按照自己的意愿去做?


代码如下:

导入 SwiftUI结构内容视图:查看{@State 私有变量选择 = 0var主体:一些视图{TabView(selection: $selection){文本(第一次查看").onAppear(){打印(第一")}.tabItem {文本(第一")}.tag(0)文本(第二视图").tabItem {文本(第二")}.tag(1)}}}struct ContentView_Previews: PreviewProvider {静态 var 预览:一些视图 {内容视图()}}


添加:

我在 SceneDelegate.swift<中使用 sceneWillEnterForegroundsceneWillResignActive/p>

但在这种情况下,当应用程序成为前台时,SecondView 也能正常工作.而且我想修改代码以仅当应用程序成为具有 FirstView 的前台时才能使用该功能.

有没有办法做到这一点?

SceneDelegate.swift

func sceneDidBecomeActive(_scene: UIScene) {打印(变得活跃")}funcsceneWillEnterForeground(_场景:UIScene){打印(前景")}


Xcode:11.7 版

斯威夫特:斯威夫特 5

解决方案

您可以使用 @EnvironmentObject 来跟踪应用程序状态(通过观察通知):

class AppState: ObservableObject {@Published var isActive = true私有变量观察者 = [NSObjectProtocol]()在里面() {观察者.追加(NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { _ inself.isActive = 真})观察者.追加(NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { _ inself.isActive = false})}去初始化{观察者.forEach(NotificationCenter.default.removeObserver)}}

您需要在 SceneDelegate 中创建它(仅一次)并作为 @EnvironmentObject 传递给 ContentView:

让 appState = AppState()让 contentView = ContentView().environmentObject(appState)

现在你可以在任何你想要的视图中使用@EnvironmentObject:

struct FirstView: View {@EnvironmentObject var appState: AppStatevar主体:一些视图{文本(第一个视图,isActive:\(appState.isActive.description)")}}

I'm currently developing an application using SwiftUI.

I want to use a method when a view appears.

In the case of the code I attached below, I can use the print method when the app is booted and done some transitions between pages.


But I want to use the print method when I reopen the app like below:

  • 1: run the code on a simulator (I can see the print method works).

  • 2: press a home button.

  • 3: open the app with tap the app icon (I can't see the print method works ).

    (*) I want to use the print method here.

How can I do it as I want in this case?


here is the code:

import SwiftUI

struct ContentView: View {
    
    @State private var selection = 0
 
    var body: some View {
        TabView(selection: $selection){
            Text("First View")
                .onAppear(){
                    print("First")
            }
                .tabItem {
                        Text("First")
                }
                .tag(0)
            
            Text("Second View")
                .tabItem {
                        Text("Second")
                }
                .tag(1)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


ADD:

I found a way to use some function when the app becomes a foreground from a background using sceneWillEnterForeground or sceneWillResignActive in SceneDelegate.swift

But in this case, when the app becomes a foreground with the SecondView also works function. And I want to modify the code to work the function only when the app becomes foreground with the FirstView.

Is there any way to do that?

SceneDelegate.swift

func sceneDidBecomeActive(_ scene: UIScene) {
        print("BecomeActive")
    }
func sceneWillEnterForeground(_ scene: UIScene) {
        print("Foreground")
    }


Xcode: Version 11.7

Swift: Swift 5

解决方案

You may use an @EnvironmentObject to track the application state (by observing notifications):

class AppState: ObservableObject {
    @Published var isActive = true

    private var observers = [NSObjectProtocol]()

    init() {
        observers.append(
            NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { _ in
                self.isActive = true
            }
        )
        observers.append(
            NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { _ in
                self.isActive = false
            }
        )
    }
    
    deinit {
        observers.forEach(NotificationCenter.default.removeObserver)
    }
}

You need to create this (once only) in the SceneDelegate and pass to the ContentView as an @EnvironmentObject:

let appState = AppState()
let contentView = ContentView().environmentObject(appState)

Now you can use the @EnvironmentObject in any view you want:

struct FirstView: View {
    @EnvironmentObject var appState: AppState

    var body: some View {
        Text("First View, isActive: \(appState.isActive.description)")
    }
}

这篇关于如何使用没有任何页面转换或任何重启应用程序的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆