0

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() {}
   
}
1
  • Try setting the frame of the spacer, and put it before all the buttons. Commented Feb 9, 2021 at 17:38

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.