top of page
  • Yazarın fotoğrafıÖmer Çağrı Şayir

LazyHStack and LazyVStack

Hello everyone. Long time, no see. I have never written a Medium article in English before. I hope you will like it. Enjoy!


LazyHStack and LazyVStack are components used in SwiftUI. They are similar to HStack and VStack which align children horizontally and vertically, respectively.

However, these “Lazy” versions of the stacks have a specific behavior: they do not build any of their views that are not visible. In other words, they load their children on demand, which can be more efficient when dealing with a large number of views.


In addition to these, they do not take up all the space offered to them, even if they have flexible views (stacks, spacers, etc.) inside. You’d use these when you have a stack that is in ScrollView.

Also, there is one important layout difference: lazy stacks always take up as much space as is available in our layouts, whereas regular stacks take up only as much space as is needed. It stops lazy stacks from having to adjust their size if a new view is loaded that wants more space.

LazyVStack is suitable for vertical lists like feeds or long forms.

ScrollView {
  LazyVStack {
    ForEach(1...100, id: \.self) { index in 
      Text("Item \(index)")
    }
  }
}

In this example, we have a vertical list of 100 text elements. The “LazyVStack” loads elements as the user scrolls down, making it efficient for displaying a large number of views.



LazyHStack is ideal for horizontal scrolling lists or carousels.

ScrollView(.horizontal) {
    LazyHStack {
        ForEach(1...100, id: \.self) { index in
            Text("Item \(index)")
        }
    }
}

This example creates a horizontally scrollable view with 100 text elements. The "LazyHStack" ensures that only the elements visible on the screen are rendered, saving memory and improving performance.

Key Points
  • Both “LazyVStack” and “LazyHStack” are beneficial for improving performance in large collections.

  • They differ from “HStack” and “VStack” mainly in their on-demand loading behavior.


By using these components, you can create efficient and responsive layouts in your iOS apps, which is crucial when dealing with dynamic or extensive data sets.



Thank you for your time. I hope this article is useful for you. See you next time!



[1]: Stanford | CS193p — Developing apps for iOS, Lecture 6 (2023)

[2]: Hacking with iOS — SwiftUI Edition (02/03/2022), Paul Hudson

[3]: ChatGPT by OpenAI, 2023.

3 görüntüleme0 yorum

Comments


bottom of page