我的文件LazyVGrid中有类似的内容SearchView.swift
let layout = [
GridItem(.flexible()),
GridItem(.flexible())
]
NavigationView {
ZStack {
VStack {
....Some other stuff here
ScrollView (showsIndicators: false) {
LazyVGrid(columns: layout) {
ForEach(searchViewModel.allUsers, id: \.uid) { user in
NavigationLink(destination: ProfileDetailedView(userData: user)) {
profileCard(profileURL: user.profileURL, username: user.username, age: user.age, country: user.city)
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的 profileCard.swift 看起来像:
var body: some View {
ZStack {
Image.image(urlString: profileURL,
content: {
$0.image
.resizable()
.aspectRatio(contentMode: .fill)
}
)
.frame(width: 185, height: 250)
.overlay(
LinearGradient(gradient: Gradient(colors: [.clear, .black]), startPoint: .center, endPoint: .bottom)
)
.overlay(
VStack (alignment: .leading) {
Text("\(username.trimmingCharacters(in: .whitespacesAndNewlines)), ")
.font(.custom("Roboto-Bold", size:14))
.foregroundColor(Color.white)
+ Text("\(age)")
.font(.custom("Roboto-Light", size:14))
.foregroundColor(Color.white)
HStack {
Text("\(country)")
.font(.custom("Roboto-Light", size:14))
.foregroundColor(.white)
}
}
.padding(.leading, 15)
.padding(.bottom, 15)
,alignment: .bottomLeading
)
.cornerRadius(12)
}
}
Run Code Online (Sandbox Code Playgroud)
这会在不同的屏幕尺寸上产生 2 个不同的空间:
iPhone 12:
iPhone 12 Pro 最大
我试图在所有设备上的卡片之间(水平和垂直)以及卡片周围获得相同的间距,对实现这一目标有什么帮助吗?
更新
按照@Adrien 的示例让我更接近问题,但是当我使用图像时,结果完全改变
let columns = Array(repeating: GridItem(.flexible(), spacing: 20, alignment: .center), count: 2)
ScrollView (showsIndicators: false) {
LazyVGrid(columns: columns, spacing: 20) {
ForEach(searchViewModel.allUsers, id: \.uid) { user in
NavigationLink(destination: ProfileDetailedView(userData: user)) {
HStack {
Image("placeholder-avatar")
.resizable()
.aspectRatio(contentMode: .fill)
}
.frame(maxWidth: .infinity, minHeight: 240) // HERE 1
.background(Color.black)
.cornerRadius(25)
}
}
}.padding(20)
}
Run Code Online (Sandbox Code Playgroud)
的数组GridItem仅固定每个单元格的容器的行为。这里它是灵活的,但这并不意味着它会修改它的内容。
它包含的内容View可以具有三种不同的行为:
Rectangle、Image().resizable()或任何带有.frame(maxWidth: .infinity, maxHeight: .infinity))修饰符的视图。Text,或HStack)。.frame(width: 185, height: 250))如果您希望单元格之间具有相同的间距(垂直和水平),无论使用什么设备,您的内容都ProfileDetailedView必须适应其容器:
您必须修改您的单元格,使其采用行为1。
您可以使用spacing您的参数GridItem(水平间距)和LazyVGrid(垂直)。
例子:
struct SwiftUIView5: View {
let columns = Array(repeating: GridItem(.flexible(), spacing: 20, alignment: .center), count: 2) // HERE 2
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 20) { // HERE 2
ForEach((1...10), id: \.self) { number in
HStack {
Text(number.description)
.foregroundColor(.white)
.font(.largeTitle)
}
.frame(maxWidth: .infinity, minHeight: 200) // HERE 1
.background(Color.black)
.cornerRadius(25)
}
}
.padding(20) // HERE 2
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4842 次 |
| 最近记录: |