我有一个watchOS应用程序,它使用以下布局:
NavigationView {
if !HKHealthStore.isHealthDataAvailable() {
ContentNeedHealthKitView()
} else if !isAuthorized {
ContentUnauthorizedView()
} else {
TabView(selection: $selection) {
WeightView()
.navigationTitle("Weight")
.tag(1)
.onAppear {
print("Appear!")
}
.onDisappear {
print("Disappear!")
}
SettingsView()
.navigationTitle("Settings")
.tag(2)
}
}
}
不幸的是,OnAppear
和OnDisappear
操作只有在第二次从一个视图转换到另一个视图后才执行。第一次向右滑动时,不会发生任何事情。
您应该提供一个最小的可复制示例(请参阅https://stackoverflow.com/help/minimal-reproducible-example)。
您的行也会产生编译器错误。使用onAppear
的正确方法如下:
.onAppear {
}
这是一个工作示例,一切都按预期进行。您还应该将onAppear
ViewModifier放置到子视图中。
import SwiftUI
struct WeightView: View {
var body: some View {
Text("WeightView")
.onAppear {
print("Appear!")
}
.onDisappear {
print("Disappear!")
}
}
}
struct SettingsView: View {
var body: some View {
Text("SettingsView")
}
}
struct ContentView: View {
@State var selection = 1
@State var isAuthorized = false
var body: some View {
NavigationView {
if !isAuthorized {
Button("authorize") {
isAuthorized.toggle()
}
} else {
TabView(selection: $selection) {
WeightView()
.navigationTitle("Weight")
.tag(1)
SettingsView()
.navigationTitle("Settings")
.tag(2)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}