dimanche 12 avril 2020

SwiftUI performance issue showing conditional views in Items in a ForEach loop embedded in aScrollView

Working with SwiftUI:

I have a list of views in a ScrollView that I am creating using a ForEach loop. I want to show or hide a number of little flags depending on 4 different Bool properties in the struct I am using as the model for the objects in the list. The problem I'm having is the more If-statements I add, the worse the performance gets. With no If-statements the list loads without a hitch. I'm running into this problem with only 120 items in the list. I would love help figuring out what I'm doing wrong!

Here is an example of the Content View with the ScrollView and loop:

struct ContentView: View {
  @ObservedObject var model = Model()


  var body: some View {
    ScrollView(.vertical, showsIndicators: true){
      VStack(spacing: 10){
        ForEach(model.list){ item in
          ItemView(item: item)
        }
      }
    }
  }// end body
} // end struct

And the Item Views and Struct I'm using as the model.

struct ListData: Identifiable {
  var id = UUID()
  var title: String
  var subtitle: String
  var isTrue: Bool
  var isAlsoTrue:Bool
}

struct ItemView: View {
  var item: ListData

  var body: some View {
    VStack(alignment: .leading){
      Text(item.title)
      HStack{
        if item.isTrue{
          FlagView(text: "True")
        }
        if item.isAlsoTrue{
          FlagView(text: "Also")
        }
        Text(item.subtitle)
        Spacer()
      }
      .font(.system(size: 12, weight: .semibold))
    }
    .font(.system(size: 14, weight: .semibold))
  }
}

struct FlagView: View {
  var text: String
  var body: some View {
    Text(text)
      .padding(2)
      .foregroundColor(.white)
      .background(RoundedRectangle(cornerRadius: 2).foregroundColor(.gray))
  }
}

The Actual objects have 4 Bool properties I want to use. Is there a better way to hide or show these flags in my list? Any help figuring out what's wrong with the performance is greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire