试图在一堆卡片上重新创建下一项/前一项。我在ZStack里有我的卡片。我遇到的问题是,默认情况下,ZStack是按相反顺序排列的(数组中的第一项位于堆栈的底部)。
下面是当前代码的样子:
数据
var userData: [User] = [
User(id: 0, firstName: "Cindy", lastName: "Jones", age: 23, mutualFriends: 4, imageName: "image1", occupation: "Coach"),
User(id: 1, firstName: "Mark", lastName: "Bennett", age: 27, mutualFriends: 0, imageName: "image2", occupation: "Insurance Agent"),
User(id: 2, firstName: "Clayton", lastName: "Delaney", age: 20, mutualFriends: 1, imageName: "image23, occupation: "Food Scientist"),
]内容视图(数据在其中传递)
CardsView(users: userData).tab(title: "Tinder Cards", image: "music.note")卡栈
struct CardStack: View {
@State var users: [User]
var body: some View {
ZStack {
ForEach(self.users, id: \.self) { user in
if user.id > self.maxID - 4 { //only show 4 at a time
CardView(user: user)
}
}
}
}
} 目前,我可以想出两种方法来解决这个问题:
array.
因为数组对所有其他屏幕的顺序都是正确的,所以第一个选项似乎是个坏主意(如果有很多卡片,可能会慢一点)。尽管如此,我已经尝试用CardsView(users: userData.reversed())将数据传递到视图中,但它似乎没有任何效果。
第二个选择是更改个人卡上的zIndex。在这个例子中,每个用户都有一个Int作为ID,所以我想我可以这样否定它,但是它没有任何效果:
ZStack {
ForEach(self.users, id: \.self) { user in
if user.id > self.maxID - 4 {
CardView(user: user)
.zIndex(Double(user.id) * -1)
}
}
}而且,奇怪的是,如果我将id更改为负值,当它们的数组像User(id: -1,一样创建时,它们根本就不可见。有人知道我在这里做错了什么吗?
谢谢:3
发布于 2021-09-25 17:19:51
import SwiftUI
struct ReverseZView: View {
let values: [Int] = [0,1,2,3,4,5,6,7,8,9]
let colors: [Color] = [.red,.yellow,.orange,.green,.blue,.gray,.black]
var body: some View {
VStack{
ZStack{
ForEach(Array(values.enumerated()), id:\.offset, content: { (index, value) in
Circle()
.overlay(Text(value.description).foregroundColor(.white))
.frame(width: 40)
.foregroundColor(colors.randomElement()!)
//use the index to find the opposite value
.zIndex(Double(values.count - index))
})
}
ZStack{
ForEach(Array(values.enumerated()), id:\.offset, content: { (index, value) in
Circle()
.overlay(Text(value.description).foregroundColor(.white))
.frame(width: 40)
.foregroundColor(colors.randomElement()!)
//Just making the index negative should also reverse
.zIndex(-Double(index))
})
}
}
}
}https://stackoverflow.com/questions/69328078
复制相似问题