如何在TabView SwiftUI中为视图保存列表状态

时间:2020-03-13 09:39:15

标签: swiftui swiftui-list

我在SwiftUI中有一个带有标签的TabView。当我从一个FirstView滚动列表并点击另一个选项卡,然后切换回FirstView时,FirstView中的列表会自动重画并滚动到顶部。如何解决该问题。

enter link description here

这是FirstView

 var body: some View {
    NavigationView {
        List {
            ForEach(feed) { game in
                FeedCardItem(gameModel: game)
                    .frame(width: UIScreen.main.bounds.width - 30, height: 400)
            }
        }
        .navigationBarTitle(Text("Новое сегодня"))
    }
}

这是TabView实现

    TabView (selection: $currentTab) {
        FeedView().tabItem {
            Image(systemName: currentTab == 0 ? "house.fill" : "house")
                .renderingMode(.original)
                .imageScale(.large)
        }.tag(0)

        RecommendationsView().tabItem {
            Image(systemName: currentTab == 1 ? "gamecontroller.fill" : "gamecontroller")
                .renderingMode(.original)
                .imageScale(.large)
        }.tag(1)

        SearchView().tabItem {
            Image(systemName: currentTab == 2 ? "flame.fill" : "flame")
                .renderingMode(.original)
                .imageScale(.large)
        }.tag(2)

        NotificationsView().tabItem {
            Image(systemName: currentTab == 3 ? "bell.fill" : "bell")
                .renderingMode(.original)
                .imageScale(.large)
        }.tag(3)

        ProfileView().tabItem {
            Image(systemName: currentTab == 4 ? "person.fill" : "person")
                .renderingMode(.original)
                .imageScale(.large)
        }.tag(4)

    }.edgesIgnoringSafeArea(.top)
}

3 个答案:

答案 0 :(得分:1)

我认为无法通过SwiftUI实现。替代方法是在UIKit中创建tabview并在SwiftUI中使用它。

我创建了一个快速示例,说明如何实现此目标以及如何解决您的问题。让我知道您是否还有其他问题。

我已将代码上传到GitHub。 https://github.com/subhan5/TabTest

在上传的代码中,文件夹UITab包含通过UIKit创建的tabview。 在ContentView中,我将其转换为UIViewControllerRepresentable并使用它。

答案 1 :(得分:0)

可以通过以下描述的UITableViewConfigurator来实现:Scroll SwiftUI List to new selection

但是,当然...这使用了UIViewControllerRepresentable...。

答案 2 :(得分:0)

我遇到了同样的问题,找到了这个解决方案:https://kavsoft.dev/SwiftUI_2.0/Tab_Bar

基本上,您可以隐藏一个选项卡的内容,而不是将其替换为另一个内容视图。我认为这个解决方案有点棘手但有效。