使按钮跨越 VStack [英] Making Button span across VStack

查看:29
本文介绍了使按钮跨越 VStack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下 SwiftUI 视图:

HStack {...虚拟堆栈{文本域 { ... }SecureField { ... }按钮 { ... }}...}

我在 Button 中添加了一个 .background(Color.green),正如您所看到的,视图与文本非常贴合.>

我想知道是否有一种方法可以调整按钮的宽度,使其填充 VStack - 类似于 UIStackView 的 .fill 模式.

解决方案

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

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

Button(action: handleSignInAction) {文本(登录")}.frame(maxWidth: .infinity).background(颜色.绿色)


2019 年的旧答案:

您可以使用带有 TextSpacerHStack 来获得一个 Button 填充宽度它的父级:

Button(action: handleSignInAction) {堆栈{垫片()文本(登录")垫片()}}.背景(颜色.绿色)

I currently have the following SwiftUI view:

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

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.

解决方案

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)

这篇关于使按钮跨越 VStack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆