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

查看:137
本文介绍了让我们在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天全站免登陆