Search code examples
swiftswiftuihstack

How can I add fixed-width space to beginning of HStack?


In SwiftUI I am adding buttons to an HStack. I want a space of a fixed width at the beginning of the HStack. Currently the buttons are directly up against the left edge of the screen and I want a space of 64px before the first button. I cannot seem to find an answer to this, my Google-Fu may be failing me.

Here is what I have:

struct MyView: View {
   var body: some View {
      HStack(alignment: .center, spacing: 12, content: {
         Button(action: doThis) {
            Image("this").resizable().aspectRatio(contentMode: .fit)
         }.frame(width: 38, height: 38, alignment: .center)
         Button(action: doThat) {
            Image("that").resizable().aspectRatio(contentMode: .fit)
         }.frame(width: 38, height: 38, alignment: .center)
         Spacer()
      })
   }
   
   func doThis() {}
   
   func doThat() {}
   
}

Solution

  • Just add some padding on the left.

    struct ContentView: View {
       var body: some View {
          HStack(alignment: .center, spacing: 12, content: {
             Button(action: doThis) {
                Image("this").resizable().aspectRatio(contentMode: .fit)
             }.frame(width: 38, height: 38, alignment: .center)
    
             .padding(.leading, 64) /// here!
            
            
             Button(action: doThat) {
                Image("that").resizable().aspectRatio(contentMode: .fit)
             }.frame(width: 38, height: 38, alignment: .center)
             Spacer()
          })
       }
       
       func doThis() {}
       
       func doThat() {}
       
    }
    
    Before After
    No space on left Space on left