微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 SwiftUI 中创建带有方形单元格的 2 列网格

如何解决如何在 SwiftUI 中创建带有方形单元格的 2 列网格

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

enter image description here

我像这样创建了单元格。

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 这样的小屏幕上,单元格是重叠的。

enter image description here

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

enter image description here

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

解决方法

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))
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。