15

我目前有以下 SwiftUI 视图:

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

在此处输入图像描述

我在 中添加了一个.background(Color.green)Button如您所见,该视图与文本非常贴合。

我想知道是否有办法调整按钮的宽度以使其充满-VStack类似于.fill.UIStackView

4

7 回答 7

29

最好的方法是通过.frame(maxWidth: .infinity) https://developer.apple.com/documentation/swiftui/view-layout

如果您希望按钮不居中,则需要指定alignment.
例如:.frame(maxWidth: .infinity, alignment: .leading)

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

2019年的旧答案:

您可以使用 a和HStacka来获得填充其父级宽度的 a:TextSpacerButton

Button(action: handleSignInAction) {
    HStack {
        Spacer()
        Text("Sign In")
        Spacer()
    }
}.background(Color.green)
于 2019-06-06T07:17:32.080 回答
13

@d.felber 的答案几乎是完整的,但你需要Spacer()在每一侧都居中:

Button(action: {
    // TODO: ...
}) {
    HStack {
        Spacer()
        Text("Sign In")
        Spacer()
    }
}
于 2019-08-02T21:00:34.250 回答
9
.frame(maxWidth: .infinity)

为我做了诀窍。

于 2020-05-02T04:40:21.087 回答
5

如果您想坚持 SwiftUI 文档建议您需要使用 GeometryReader 并手动设置按钮宽度的方法。几何阅读器会针对不同设备和旋转更新其属性。

GeometryReader { geometry in
     Button().frame(width: geometry.size.width, height: 100)
}
于 2019-06-06T13:45:38.220 回答
3

将按钮文本的框架设置为 的大小,UIScreen然后在其后设置背景颜色(确保在更改框架大小完成所有样式更改,否则样式更改将仅在原始默认框架上可见)。框架大小将向上传播以将按钮的宽度也增加到屏幕的宽度。:

Button(action: {
                // Sign in stuff
            }) {
                Text("Sign In")
                .frame(width: UIScreen.main.bounds.width, height: nil, alignment: .center)
                .background(Color.green)
            }

您还可以在设置框架和背景之间添加一些负水平填充,以便从屏幕边缘偏移:

Button(action: {
                    // Sign in stuff
                }) {
                    Text("Sign In")
                    .frame(width: UIScreen.main.bounds.width, height: nil, alignment: .center)
                    .padding(.horizontal, -10.0)
                    .background(Color.green)
                }
于 2019-06-06T06:10:23.807 回答
2

像这样的东西?

Button(action: {
    // Do your login thing here
}) {
    Capsule()
        .frame(height: 44)
        .overlay(Text("Login").foregroundColor(Color.white)).padding()
}
于 2019-06-06T05:50:32.273 回答
0

我不确定是否有.fill类似的方法,UIStackView但是,如果您想要做的是在Button(或任何与此相关的视图)上提供一些间距,那么对我有用的是设置framepadding

.frame(width: 300, alignment: .center)(我们也可以在这里设置一个高度,但如果不是,它应该能够根据按钮文本推断高度。

如果您不想设置任意宽度,您还import UIKit可以使用UIScreen并获取设备全宽。(可能有一种 SwiftUI 方法可以得到这个,但目前还没有找到)

.frame(width: UIScreen.main.bounds.width, alignment: .center)

然后你可以为一些呼吸空间添加一点填充

.padding(.all, 20)

填充的问题是它会增加屏幕的额外宽度,因此我们在设置宽度时必须考虑到这一点。

(20 * 2 边从前导和尾随)

.frame(width: UIScreen.main.bounds.width - 40, alignment: .center)

(当文本覆盖到屏幕末尾或对齐方式为.leading或时,留出空间.trailing

于 2019-06-06T05:34:10.003 回答