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

时间:2019-07-18 17:38:06

标签: swift swiftui

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

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

                Text(" ......  ")
            }

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

3 个答案:

答案 0 :(得分:4)

针对Xcode 11.2和Xcode 5.0进行了完全更新

我认为viewDidLoad()等于在主体关闭中实施。
SwiftUI以viewDidAppear()viewDidDisappear()的形式为我们提供了UIKit的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!")
        }
    }
}

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

答案 1 :(得分:0)

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

var body: some View {
        NavigationView {
            Form {
                Section {
                    Text(" ......  ")
                }.onAppear { self.exampleFunction() }

答案 2 :(得分:0)

如果您要在应用启动后尝试运行某些内容,但与特定视图无关,则可以在两个不同的位置添加代码...

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

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

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

        return true
    }

或者在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 **********

        }
    }
相关问题