Home > Blockchain >  How to align the icon in grid in SwiftUI?
How to align the icon in grid in SwiftUI?

Time:12-06

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

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?

CodePudding user response:

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)
  ]

  ...
  • Related