代码之家  ›  专栏  ›  技术社区  ›  El Tomato

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

  •  0
  • El Tomato  · 技术社区  · 11 月前

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

    enter image description here

    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)
                    }
                }
            }
        }
    }
    
    1 回复  |  直到 11 月前
        1
  •  1
  •   rob mayoff    11 月前

    The overlay modifier 采取 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)
    }
    
    推荐文章