![](/img/trans.png)
[英]How to switch to another view by each element's onTapGesture of a list in SwiftUI?
[英]How to change the offset of an view using onTapGesture?
我试图在被点击时移动视图。 但不幸的是,什么也没发生。 如何使用偏移 y 轴切换它的 position?
struct Test: View {
@State var cards : [Card] = [Card(), Card(), Card(), Card(), Card(), Card()]
var body: some View {
VStack {
ZStack (alignment: .top){
ForEach (0..<cards.count) { i in
RoundedRectangle(cornerRadius: 10).frame(width: 250, height: 150)
.foregroundColor(Color.random).offset(y: self.cards[i].isFocus ? CGFloat(500) : CGFloat(i*50))
.zIndex(Double(i))
.onTapGesture {
self.cards[i].isFocus.toggle() // now the touched Card should move to an offset of y: 500, but nothing happens
}
}
}
Spacer()
}
}
}
struct Card :Identifiable{
@State var isFocus :Bool = false
var id = UUID()
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}
extension Color {
static var random: Color {
return Color(red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1))
}
}
我看到了您的代码,很抱歉,但它在许多方面都是错误的。 我会推荐你从 go 到 SwiftUI 基础知识,并了解我们如何以及何时使用@State、@ObservedObject、@Binding 等。也总是尝试将你的视图分解成最小的组件。 以下是我认为满足您要求的代码。
struct Test: View {
var cards : [Card] = [Card(), Card(), Card(), Card(), Card(), Card()]
var body: some View {
VStack {
ZStack (alignment: .top){
ForEach (0..<cards.count) { i in
CardView(card: self.cards[i], i: i)
}
}
Spacer()
}
}
}
struct CardView: View {
@ObservedObject var card: Card
let i: Int
var body: some View {
RoundedRectangle(cornerRadius: 10).frame(width: 250, height: 150)
.foregroundColor(Color.random)
.offset(y: card.isFocus ? CGFloat(500) : CGFloat(i*10))
.zIndex(Double(i))
.onTapGesture {
withAnimation {
self.card.isFocus.toggle()
}
}
}
}
class Card: ObservableObject{
@Published var isFocus: Bool = false
var id = UUID()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.