我正在尝试创建两个相同宽度的按钮,一个位于另一个上面,垂直放置。它应该是这样的:
我已经将2 Buttons
放置在一个VStack
中,它会自动扩展到较大按钮的宽度。我要做的是将按钮的宽度展开以填充VStack
的宽度,但这是我得到的结果:
VStack(alignment: .center, spacing: 20) {
NavigationLink(destination: CustomView()) {
Text("Button")
}.frame(height: 44)
.background(Color.primary)
Button(action: { self.isShowingAlert = true }) {
Text("Another Button")
}.frame(height: 44)
.background(Color.primary)
}.background(Color.secondary)
设置VStack
的宽度会扩展它,但是按钮不会展开以适应:
VStack(alignment: .center, spacing: 20) {
...
}.frame(width: 320)
.background(Color.secondary)
所以我的问题是:
除了手动设置布局中每个项目的框架之外,还有其他方法吗?
我宁愿不必具体说明每一项,因为这将变得很难管理。
发布于 2019-07-19 09:43:37
将.infinity
设置为maxWidth
,可以使用frame(minWidth: maxWidth: minHeight:)
API进行子视图展开以填充:
VStack(alignment: .center, spacing: 20) {
NavigationLink(destination: CustomView()) {
Text("Button")
}.frame(minWidth: 100, maxWidth: .infinity, minHeight: 44)
.background(Color.primary)
Button(action: { self.isShowingAlert = true }) {
Text("Another Button")
}.frame(minWidth: 100, maxWidth: .infinity, minHeight: 44)
.background(Color.primary)
}.frame(width: 340)
.background(Color.secondary)
发布于 2020-12-16 16:36:28
您必须在按钮内的maxWidth: .infinity
本身上使用带有Text
的框架修饰符,这将迫使Button
尽可能宽:
VStack(alignment: .center, spacing: 20) {
NavigationLink(destination: CustomView()) {
Text("Button")
.frame(maxWidth: .infinity, height: 44)
}
.background(Color.primary)
Button(action: { self.isShowingAlert = true }) {
Text("Another Button")
.frame(maxWidth: .infinity, height: 44)
}
.background(Color.primary)
}.background(Color.secondary)
这在iOS中有效,但在使用默认按钮样式的macOS中不起作用,该样式使用AppKit的NSButton
,因为它拒绝再变宽(或更高)。macOS的诀窍是在按钮(或NavigationLink
)上使用.buttonStyle()
修饰符,并使您自己的自定义按钮样式如下所示:
struct MyButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.background(configuration.isPressed ? Color.blue : Color.gray)
}
}
您必须将框架修饰符应用于Text
视图而不是按钮本身的原因是,该按钮更愿意坚持其内容的大小,而不是包含该按钮的视图所建议的大小。这意味着,如果将框架修饰符应用于按钮,而不是应用其中的Text
,则该按钮实际上将保持与Text
相同的大小,而.frame
返回的视图将展开以填充包含该视图的视图的宽度,因此您将无法点击/单击Text
视图边界外的按钮。
https://stackoverflow.com/questions/57109784
复制相似问题