SwiftUI生命周期

2,017 阅读1分钟

前言

我们在做UIKit程序的时候经常用到viewDidload viewWillAppear 等等

这些东西怎么在swiftUI中使用呢?

Apple Developer定义

func onAppear(perform: (() -> Void)?) -> some View

Adds an action to perform when this view appears.

在view出现的时候调用,特别时候ScrollView的子View

func onDisappear(perform: (() -> Void)?) -> some View

Adds an action to perform when this view disappears.

在view消失的时候调用,特别时候ScrollView的子View

具体使用

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView(content: {
            Text("aaa").navigationBarTitle("Libaray").navigationBarItems(leading: Button(action: {
            }, label: {
                Image("add")
            }))
        }).onAppear {
            
        }
    }
}

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

struct ContentView: View {
    var body: some View {
        NavigationView(content: {
            Text("aaa").navigationBarTitle("Libaray").navigationBarItems(leading: Button(action: {
            }, label: {
                Image("add")
            }))
        }).onAppear {
            
        }
    }
}

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