如何在使用 SwiftUI 时调用“viewDidLoad”时运行函数

vTo*_*ToM 12 swift swiftui

我正在尝试在应用程序完成加载后运行一个函数,例如viewDidLoad,但我现在正在使用 SwiftUI 而我没有viewDidLoad. 我现在该怎么做?

var body: some View {
    NavigationView {
        Form {
            Section {
                self.exampleFunction()

                Text(" ......  ")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想从该函数中获取一些信息并将其呈现在文本中。但我这样做的方式是错误的。这不是建筑。

Bra*_*ton 17

您可以使用.onAppear { ... }在视图出现时执行任意代码:

var body: some View {
        NavigationView {
            Form {
                Section {
                    Text(" ......  ")
                }.onAppear { self.exampleFunction() }
Run Code Online (Sandbox Code Playgroud)

  • 好答案。但这是否适合像“UIKit”这样的所有情况?在我看来——我可能是错的——OP 的想法太像“UIKit”编码了。例如,假设您希望从“onAppear”加载 NSURL 内容。这行得通吗?`snapper` 根本不等于 `viewDidLoad`。两个不同的堆栈,两个不同的 API。编辑:不要忘记,*每次*该视图出现时都会发生 - `onAppear` 关闭。`viewDidLoad` 仅在每次加载 UIView... 时发生。 (3认同)

小智 8

如果您尝试在应用程序启动后运行某些内容并且与特定视图无关,您可以在两个不同的地方添加代码......

在 AppDelegate.swift 中,第一个函数在 App 启动后被调用......

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // ******** Run your function here **********

        return true
    }
Run Code Online (Sandbox Code Playgroud)

或者在 SceneDelegate.swift 中,第一个函数实际上将根视图设置为原始 ContentView...

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Use a UIHostingController as window root view controller
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: ContentView())
            self.window = window

        // ******** Add code here before root view is shown **********

            window.makeKeyAndVisible()

        // ******** Add code here after root view is shown **********

        }
    }
Run Code Online (Sandbox Code Playgroud)


Zgp*_*ace 6

对 Xcode 11.2、Xcode 5.0 进行了全面更新,

我认为这viewDidLoad()正好等于在 body 闭包中实现。
SwiftUI为我们提供了等同的UIKit的viewDidAppear()和viewDidDisappear()在形式onAppear()和onDisappear()。您可以将任何代码附加到您想要的这两个事件上,SwiftUI 会在它们发生时执行它们。

例如,这将创建两个使用onAppear()和onDisappear()打印消息的视图,并带有一个在两者之间移动的导航链接:

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: DetailView()) {
                    Text("Hello World")
                }
            }
        }.onAppear {
            print("ContentView appeared!")
        }.onDisappear {
            print("ContentView disappeared!")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

参考:https : //www.hackingwithswift.com/quick-start/swiftui/how-to-respond-to-view-lifecycle-events-onappear-and-ondisappear