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