TabView horizontal paged list. Out of sync, two issues

Viewed 15

I use a TabView to simulate a horizontal scrolling paged list. This work fine. But I want to change the background, according to the currently active tab. I utilise .onAppear() for this, but this results in the images not being in sync with the item in the current tab (see video: https://youtube.com/shorts/aQxrErRmCi8?feature=share)

Basically, it should only change the background whenever the tab is 'fully' selected and centered on screen. Not as soon as the next or previous tab comes onto screen just a few pixels.

Secondly, I want to be able to set the selected programmatically, for instance after I insert a new object, I want to select the first tab. How Can I achieve that. The tabs have the id of my item (game) as tag.

Relevant code:

@State private var backgroundImage = AppImages.gameDefaultBackgroundImage

    @ViewBuilder var tabList: some View {
        TabView {
            ForEach(gamesViewModel.games) { game in
                GameCardView(game: game)
                    .tag(game.id)
                    .onAppear {
                        withAnimation(.easeInOut) {
                            backgroundImage = gamesViewModel.getGameImageCoreData(for: game)
                        }
                    }
                    .listRowBackground(Color.clear)
                    .frame(width: getScreenRectangle().width - 20)
                    .onTapGesture { showAnnotationsView(for: game) }
                    .onLongPressGesture(minimumDuration: 0.15) { gameDetailsView(for: game) }
            }
        }
        .tabViewStyle(.page(indexDisplayMode: .never))
    }

If more code is needed, please ask ...

0 Answers
Related