SwiftUI 提供了 .onAppear()
修饰符,用于在视图显示时运行闭包代码。
例如,以下代码在视图显示时打印一条消息:
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.onAppear {
print("View appeared!")
}
}
}
在视图出现时,会看到控制台输出:
View appeared!