【问题标题】:How to create a 2 column grid with square shaped cells in SwiftUI如何在 SwiftUI 中创建带有方形单元格的 2 列网格
【发布时间】:2021-02-16 12:13:12
【问题描述】:

我正在尝试使用 Grid 在 SwiftUI 中复制此 UI。

我是这样创建单元格的。

struct MenuButton: View {
    let title: String
    let icon: Image
    
    var body: some View {
        Button(action: {
            print(#function)
        }) {
            VStack {
                icon
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 60, height: 60)
                Text(title)
                    .foregroundColor(.black)
                    .font(.system(size: 20, weight: .bold))
                    .multilineTextAlignment(.center)
                    .padding(.top, 10)
            }
        }
        .frame(width: 160, height: 160)
        .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.fr_primary, lineWidth: 0.6))
    }
}

网格也是如此。

struct LoginUserTypeView: View {
    private let columns = [
        GridItem(.flexible(), spacing: 20),
        GridItem(.flexible(), spacing: 20)
    ]
    
    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns, spacing: 30) {
                ForEach(Menu.UserType.allCases, id: \.self) { item in
                    MenuButton(title: item.description, icon: Image(item.icon))
                }
            }
            
            .padding(.horizontal)
            .padding()
        }
    }
}

但在 iPod 等较小的屏幕上,单元格是重叠的。

在更大的 iPhone 屏幕上,间距仍然不正确。

我必须进行哪些调整,以便在每个屏幕尺寸中,单元格都以正确的方形显示,并且所有边的间距相等?

【问题讨论】:

标签: ios arrays swift lazyvgrid


【解决方案1】:

MenuButton 具有固定的宽度和高度,这就是它行为不正确的原因。


您可以为此使用.aspectRatio.frame(maxWidth: .infinity, maxHeight: .infinity)

struct MenuButton: View {
    let title: String
    let icon: Image

    var body: some View {
        Button(action: {
            print(#function)
        }) {
            VStack(spacing: 10) {
                icon
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(maxWidth: 60, maxHeight: 60)
                Text(title)
                    .foregroundColor(.black)
                    .font(.system(size: 20, weight: .bold))
                    .multilineTextAlignment(.center)
            }
            .padding()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .aspectRatio(1, contentMode: .fill)
        .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color. fr_primary, lineWidth: 0.6))
    }
}

【讨论】:

  • 感谢您的回复。这确实解决了我的单元格大小问题。不过有个小问题。即使单元格调整大小,里面的内容(图像和文本)仍然是相同的大小。所以在较小的屏幕上,它看起来像this。有没有办法调整这些元素的大小以适应单元格?
  • 我尝试将纵横比设置为Text 对象。 It's pushing out the image.
  • @Isuru 我假设你想让你的按钮保持方形。
猜你喜欢
  • 1970-01-01
  • 2014-08-17
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 2023-03-12
  • 2018-07-13
相关资源
最近更新 更多