让我们在 MacOS AppKit 上的 SwiftUI 中使用所有可用宽度的按钮 [英] Let use a button all available width in SwiftUI on MacOS AppKit

查看:22
本文介绍了让我们在 MacOS AppKit 上的 SwiftUI 中使用所有可用宽度的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个这样的布局:

I want to define a layout like this:

如何让按钮获取所有可用的宽度,也可以在用户调整窗口大小时.
上部三排等宽,下部一排最大.宽度

How can I let the Buttons grab all the available width, also when the user resizes the Window.
In the upper part three rows of equal width, in the lower part one row with max. width

struct TEST: View {
  let columns = [
    GridItem(.flexible()),
    GridItem(.flexible()),
    GridItem(.flexible())
  ]
  let data = ["1 Text ...",
              "2 longer Text ...",
              "3 Text ...",
              "4 Text/FA/Tra ...",
              "5 Text ...",
              "6 Text ...",
              "7 Text ...",
              "8 Text ...",
              "9  Text ...",
  ]

  var body: some View {
    VStack (alignment: .leading ){
      LazyVGrid(columns: columns) {
        ForEach(data, id: \.self) { item in
          Button(action: {print("")}){
            Text(item).background(Color.green)
          }
          .background(Color.yellow)
        }
      }
      .padding(.horizontal)
    }
    Button("even longer Text"){print("x")}
    Button("even longer Text"){print("x")}
    Button("even longer Text"){print("x")}
  }
}

推荐答案

你可以使用 .frame(maxWidth: .infinity):

Button("even longer Text") { 
    print("x") 
}
.frame(maxWidth: .infinity)


编辑

这是一个更详细的例子:

Here is a more detailed example:

var body: some View {
    VStack(alignment: .leading) {
        LazyVGrid(columns: columns) {
            ForEach(data, id: \.self) { item in
                Button(action: { print("") }) {
                    Text(item)
                        .frame(maxWidth: .infinity)
                        .contentShape(Rectangle())
                }
                .background(Color.yellow)
            }
        }
        .padding(.horizontal)
        .background(Color.blue)
    }
    Button(action: { print("x") }) {
        Text("even longer Text")
            .frame(maxWidth: .infinity)
            .contentShape(Rectangle())
    }
    .background(Color.purple)
    ...
}

我添加了颜色,因此您可以看到按钮已正确对齐.

I added colors, so you can see that buttons are aligned properly.

使用 Xcode 12.3、macOS 11.1 测试

Tested with Xcode 12.3, macOS 11.1

这篇关于让我们在 MacOS AppKit 上的 SwiftUI 中使用所有可用宽度的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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