Showing posts with label Layout. Show all posts
Showing posts with label Layout. Show all posts

Tuesday, March 22, 2022

Guide to SwiftUI layout and presentation controls in iOS

SwiftUI Layout Containers


It is always better to know about all the tools before you start your DIY project. You need to know what tools are available and what each tool can be used for. The same strategy can be applied to UI design. If you know all the available tools provided by the SwiftUI framework then you will be able to apply that knowledge to the beautiful designs that your designer has provided you with. Following are the Layout containers provided by SwiftUI.

HStack

you can refer HStack as a horizontal stack. You want to stack your controls shown in the image below. 

Horizontal plates stacking


The views in SwiftUI are aligned in a similar fashion as shown in image below

SwiftUI HStack


LazyHStack

As the name says this is a Lazy container. As the keyword, Lazy in a programming language is a strategy to delay the initialization until it is needed. The views in the LazyStack are not initialized until they are needed. 

You can try this code and see how it works. 

import SwiftUI


struct CustomText: View {

  private let index: Int

  init(index: Int) {

    print("init CustomText \(index)")

    self.index = index

  }

  var body: some View {

    Text("This is custom text view")

  }

}


struct ContentView: View {

    var body: some View {

      ScrollView(.horizontal) {

        LazyHStack {

          ForEach(0...100, id:\.self) { index in

            CustomText(index: index)

          }

        }

      }

    }

}

It should look like as shown in image below when you first run it. 

LazyHStack Image


VStack

The Stack is referred to as vertical stack e.g. as shown in the image below


Vertical Stack plates


The corresponding SwiftUI views are stacked in a similar fashion as shown in the image below.

SwiftUI VStack


LazyVStack

LazyVStack works very similar to LazyHStack, it's just that it will align the items vertically. Before you read further, I want you to try the code from the LazyHStack section and just change the LazyHStack to LazyVStack. 

Check the output in the debug window. Must be wondering what is going on there. All the items are getting rendered. 

So what should you do it fix it? Try it before looking at the code below. 

|

|

|

I am sure you have tried it. The thing is that you need to change the ScrollView to be .vertical.

import SwiftUI


struct CustomText: View {

  private let index: Int

  init(index: Int) {

    print("init CustomText \(index)")

    self.index = index

  }

  var body: some View {

    Text("This is custom text view")

  }

}


struct ContentView: View {

    var body: some View {

      ScrollView(.vertical) {

        LazyVStack(alignment: .center, spacing: 50) {

          ForEach(0...100, id:\.self) { index in

            CustomText(index: index)

          }

        }

      }

    }

}