Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak in TabView with PageTabViewStyle

I'm using a tab view using the UIPageViewController behaviour. So I defined the following model:

class WalktroughModel: Identifiable, ObservableObject {
  let id: UUID = UUID()
  let imageName: String
  let title: String

  init(imageName: String, title: String) {
      self.imageName = imageName
      self.title = title
  }
}

Now I use this swiftUI view as a child view of tab view:

struct WalktroughAsset: View {

  @StateObject var asset: WalktroughModel

  var body: some View {
      Image(asset.imageName)
          .resizable()
          .overlay(Color.black.opacity(0.43))
          .overlay(
              VStack{
                  Spacer()
                  Text(asset.title)
                      .foregroundColor(.white)
                      .font(.custom("OpenSans-regular", size: 22.0))
              }
              .padding(.bottom, 64)
          )
    }
}

In my content view I have the following:

struct ContentView: View {

   var thumbs: [WalktroughModel] = [WalktroughModel(imageName: "splash-1", title: "Concepto 1"), WalktroughModel(imageName: "splash-2", title: "Concepto 2"), WalktroughModel(imageName: "splash-3", title: "Concepto 3")]

   var body: some View {
       ZStack {
           Color.black.overlay(TabView{
               ForEach(thumbs) {
                   image in
                   WalktroughAsset(asset: image)
               }
           }
           .tabViewStyle(PageTabViewStyle())
           .padding([.bottom, .top], 32)
           )
        
       }
       .edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
    
   }
}

Now, when I build and run the memory jumps 80 mb to 160 mb when I swipe to the other view and jumps to 230 mb when I swipe to the third view. What could be happen?

Best Regards

like image 629
Alfredo Luco G Avatar asked Nov 16 '22 08:11

Alfredo Luco G


1 Answers

This code fixes a memory leak 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))

This bug is presented when you use custom view with args

like image 180
stalkermv Avatar answered Jan 03 '23 09:01

stalkermv