Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to align the icon in grid in SwiftUI?

So I have this code which basically shows three grid items next to each other,

import SwiftUI

struct ContentView: View {
  let columns = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]
  
  var body: some View {
    ScrollView {
      LazyVGrid(columns: columns, spacing: 20) {
        Button(action: {}) {
          VStack {
            Image(systemName: "tray")
              .font(.system(size: 40.0))
            Text("Item 1")
          }
        }
        
        Button(action: {}) {
          VStack {
            Image(systemName: "tray")
              .font(.system(size: 40.0))
            Text("Item 2")
          }
        }
        
        Button(action: {}) {
          VStack {
            Image(systemName: "tray")
              .font(.system(size: 40.0))
            Text("Item 935835050350")
          }
        }
      }
    }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

And it looks like this,

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As you can see the text pushes icon to the top. I want text to move down and icon’s position to remain constant i.e. aligned with the adjacent icons. How do I do that?

>Solution :

You need explicit alignment in grid items, like

struct ContentView: View {
  let columns = [
     GridItem(.flexible(), alignment: .top),     // << this !!
     GridItem(.flexible(), alignment: .top), 
     GridItem(.flexible(), alignment: .top)
  ]

  ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading