为什么在选项卡栏上单击“电视”时,TvAiringTodayView会初始化两次?有时,它仅加载一次,但大多数情况下每次都会加载。运行应用程序并单击“电视”标签栏按钮时,得到以下输出:
initMainView
initMovieMainView
initTvMainView
initTvButtonBarView
initTvAiringTodayView
initTvAiringTodayView
您可能必须尝试两次才能看到它的发生。单击时,TvAiringTodayView似乎不应该两次初始化,但是可以。
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
//Movies View
MovieMainView()
.tabItem {
Image(systemName: "film")
Text("Movies")
}
//TV View
TvMainView()
.tabItem {
Image(systemName: "tv")
Text("TV")
}
}
}
init() {
print("initMainView")
}
}
struct MovieMainView: View {
var body: some View {
VStack {
Text("MovieMainView")
}
}
init() {
print("initMovieMainView")
}
}
struct TvMainView: View {
var body: some View {
VStack {
ScrollView(.vertical, showsIndicators: false) {
TvButtonBarView()
}
}
}
init() {
print("initTvMainView")
}
}
struct TvButtonBarView: View {
@State private var selectedViewType = 0
var viewType = ["On The Air", "Top Rated", "Popular"]
var body: some View {
VStack {
Picker(selection: $selectedViewType, label: Text("Strength")) {
ForEach(0 ..< viewType.count ) {
Text(self.viewType[$0])
}
}.pickerStyle(SegmentedPickerStyle())
if selectedViewType == 0 {
TvAiringTodayView()
}
// if selectedViewType == 1 {
// TvTopRatedView()
// }
// if selectedViewType == 2 {
// TvPopularView()
// }
}
}
init() {
print("initTvButtonBarView")
}
}
struct TvAiringTodayView: View {
var body: some View {
Text("TvAiringTodayView")
}
init() {
print("initTvAiringTodayView")
}
}
答案 0 :(得分:0)
我已经对该代码进行了20多次测试,没有提到任何问题。我相信您面临的问题是某种错误。
与类不同,结构易于创建和销毁。因此,每次父级更改状态时,都会调用TvAiringTodayView的init。当selectedViewType != 0
时,该结构将从内存中清除,而当selectedViewType == 0
时,该结构再次被初始化。当stength
选择器更改状态selectedViewType
时,将创建多个初始化调用。