3

Why does a LazyHStack behaves differently than an HStack regarding the height? (same for the VStack).

import SwiftUI

struct LazyTestView: View {

   var body: some View {

      LazyHStack {

         ForEach(1...10, id: \.self) { int in
            Text("\(int)")
         }

      }
   }
}

struct LazyTestView_Previews: PreviewProvider {

    static var previews: some View {
        LazyTestView()
            .previewLayout(.sizeThatFits)
    }
}

enter image description here

Whereas with an HStack:

import SwiftUI

struct LazyTestView: View {
   var body: some View {
      HStack {
         ForEach(1...10, id: \.self) { int in
            Text("\(int)")
         }
      }
   }
}

enter image description here

One solution is to add .fixedSize() for the LazyHStack...

PS: Xcode Version 12.5 beta (12E5220o)

alpennec
  • 1,864
  • 3
  • 18
  • 25

1 Answers1

7

It was from beginning like that. Started with LazyVStack, the reason is because Lazy Stacks does not know all possible content that they are carrying, there for it takes safer approach to be prepared for any size of content, in the other hand the normal Stacks does know exactly what are their children and therefore they take a frame or size that they really needed for that, not more not less!

ios coder
  • 1
  • 4
  • 31
  • 91
  • Oh that makes sense actually! In my case, I think I can use a "normal" HStack / VStack as I don't have a lot of items in my list (max 10). Thanks for your answer! – alpennec Feb 07 '21 at 21:43
  • your welcome, I also use normal Stack if I know that I do not have tones of data, but if you are loading some data that you do not have idea how big it could be, then use definitely Lazy one, it has day and night deference in memory management. – ios coder Feb 07 '21 at 22:02