SwiftUI TabView memory footprint continuously increases when changing page

Viewed 342
struct ContentView: View {
    
    @State private var selectedIdx = 0
    
    var body: some View {
        TabView(selection: $selectedIdx) {
            ForEach(0..<5) { idx in
                Text("\(idx)")
            }
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    }
}

Environment: Xcode 12.2 iOS 14.2

TabView in SwiftUI memory continuously increases as I swipe between pages. Running instruments, I do not see any leaks but the allocation and persistent memory increases continuously.

Ideally, even if the pages are being recreated every time, the total memory consumed by the 5 pages (as in the code above) should not change.

Is this a bug in SwiftUI? Or am I missing something?

1 Answers

This code fixes a bug for me

struct TabViewWrapper<Content: View, Selection: Hashable>: View {
    @Binding var selection: Selection
    @ViewBuilder let content: () -> Content
    
    var body: some View {
        TabView(selection: $selection, content: content)
    }
}

Replace TabView(selection:) to TabViewWrapper(selection:)

TabViewWrapper(selection: $selection) {
    tabContent
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
Related