SwiftUI TabView两次调用初始化函数

时间:2020-03-05 12:20:27

标签: swiftui tabview

tabview令我很生气,希望一些天才能为您提供帮助。
默认情况下,tabview会在每次不需要的时候初始化所有视图,因此我通过添加一个惰性视图来解决它。这是我的代码

http://github.com/BellRinging/TestBug.git

import SwiftUI
struct TabViewIssue: View {

@State private var selected = 0

var body: some View {
    TabView(selection: $selected, content: {
        LazyView(TestPage(text:"Page1"))
            .tabItem {
                selected == 0 ? Image(systemName: "book.fill"):Image(systemName: "book")
                Text("Page1")
        }.tag(0)

        LazyView(TestPage(text:"Page2"))
            .tabItem {
                selected == 1 ? Image(systemName: "book.fill"):Image(systemName: "book")
                Text("Page2")
        }.tag(1)
        })
}
}



 struct TestPage: View {
    let text : String
    init(text : String){
        self.text = text
        print("init \(text)")
    }
    var body: some View {
        Text(text) //no issue for a sigle view
    }
}

struct LazyView<Content: View>: View {
let build: () -> Content
init(_ build: @autoclosure @escaping () -> Content) {
    self.build = build
}
var body: Content {
    build()
}

}

工作正常。如果切换页面,结果为“ init Page1”,“ init Page2”。
然后我将选项卡更改为指向TestPage2(唯一不同的是视图主体具有一个额外的VStack项)

LazyView(TestPage2(text:"Page2"))

///将上面的代码更改为TestPage2

struct TestPage2: View {
let text : String
init(text : String){
    self.text = text
    print("init \(text)")
}
var body: some View {
    VStack{ //If added a VStack ..tabview init call twice
        Text(text)
        Text(text)
    }
}

}

结果是
初始化Page2
初始化Page1
初始化Page1
初始化Page2

init函数被调用两次..它很奇怪

1 个答案:

答案 0 :(得分:1)

最后,我已经通过添加额外的struct

解决了该问题
 import SwiftUI
struct TabViewIssue: View {

    var body: some View {
        TabbarView2()
    }
}


struct TabbarView2: View {
    @State var selectedTab = Tab.game

    enum Tab: Int {
        case game, search, menu,edit
    }

    func tabbarItem(text: String, image: String ,selectedImage: String) -> some View {
        VStack {
            Image(systemName: image)
                .imageScale(.large)
            Text(text)
        }
    }

    var body: some View {
        TabView(selection: $selectedTab) {
            LazyView(TestPage(text:"Page1")).tabItem{
                self.tabbarItem(text: "Edit", image: "person.fill",selectedImage: "person")
            }.tag(Tab.edit)
            LazyView(TestPage2(text:"Page2")).tabItem{
                self.tabbarItem(text: "Game", image: "book.fill",selectedImage: "book")
            }.tag(Tab.game)
        }.edgesIgnoringSafeArea(.top)
    }
}