Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Button span across VStack

Tags:

swift

swiftui

I currently have the following SwiftUI view:

HStack {
  ...
  VStack {
    TextField { ... }
    SecureField { ... }
    Button { ... }
  }
  ...
}

enter image description here

I've added a .background(Color.green) to the Button, and as you can see, the view is very snug to the text.

I'm wondering if there's a way to adjust the width of the button so that it fills across VStack - something like a .fill mode for UIStackView.

like image 903
Kelvin Lau Avatar asked Jun 06 '19 04:06

Kelvin Lau


People also ask

How to set full width in SwiftUI?

To make a SwiftUI view take all available width, we use . frame() modifier with maxWidth and maxHeight set to . infinity . The result of using .

How do you stretch a button?

There are a few different ways that you can stretch a button in CSS. One way is to set the width and height of the button to 100%. Another way is to set the padding of the button to a larger value. If I remove the page width property, the button will fill it.

What is a Hstack?

A view that arranges its subviews in a horizontal line.

How do I give a margin in SwiftUI?

You need to use . padding modifier for margin. In your code, you have to add padding inside your ScrollView. After that, inside BoxViewTable, you need to add .


1 Answers

The best way to do this is via .frame(maxWidth: .infinity) https://developer.apple.com/documentation/swiftui/view-layout

If you want the button not to be centered you need to specify alignment.
e.g.: .frame(maxWidth: .infinity, alignment: .leading)

Button(action: handleSignInAction) {
    Text("Sign In")
}
.frame(maxWidth: .infinity)
.background(Color.green)

Old answer from 2019:

You could use a HStack with a Text and Spacer to get a Button that fills the width of its parent:

Button(action: handleSignInAction) {
    HStack {
        Spacer()
        Text("Sign In")
        Spacer()
    }
}.background(Color.green)
like image 165
d.felber Avatar answered Sep 30 '22 17:09

d.felber