如何在 LazyVGrid 中获取 GridItem 视图的大小或在视图角附近显示数字

问题描述 投票:0回答:1

我在

Buttons
中有一堆
LazyVGrid
,如下图所示。我想在按钮的左上角附近显示一个数字。对于特定的 iOS 设备型号,我可以仅偏移数字的位置。但如果我有 iPad,这种方法可能会大错特错。有没有办法获得
GridItem
View
的大小?如果没有,是否有一种有效的方法可以在左上角显示数字,无论设备型号如何?谢谢。

import SwiftUI

struct ContentView: View {
    private let cols = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]
    
    var body: some View {
        LazyVGrid(columns: cols) {
            ForEach(0...30, id: \.self) { item in
                Button {
                    
                } label: {
                    Image(systemName: "\(item).circle.fill")
                         .resizable()
                         .aspectRatio(contentMode: .fit)
                         .foregroundColor(.orange)
                    
                }
                .overlay {
                    Text("0")
                        .font(.caption)
                        .foregroundStyle(.blue)
                        .offset(x: -20, y: -20)
                }
            }
        }
    }
}
ios swiftui overlay lazyvgrid
1个回答
0
投票

overlay
修饰符采用
alignment
参数,默认为
.center
。尝试通过
.topLeading
而不是使用
.offset
:

Button { } label: {
    Image(systemName: "\(item).circle.fill")
         .resizable()
         .aspectRatio(contentMode: .fit)
         .foregroundColor(.orange)
    
}
.overlay(alignment: .topLeading) {
//       ^^^^^^^^^^^^^^^^^^^^^^ 🟢 ADD THIS
    Text("0")
        .font(.caption)
        .foregroundStyle(.blue)
}
© www.soinside.com 2019 - 2024. All rights reserved.