简体   繁体   中英

How to change the offset of an view using onTapGesture?

I am trying to move a view when it is being tapped. But unfortunately nothing happens. How do I toggle the position of it using the offset y axis?

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

I see your code and I am sorry to say but its wrong in many aspects. I would recommend you to go through SwiftUI basics and understand how and when we use @State, @ObservedObject, @Binding etc. Also always try to break your Views into the smallest components. Below is the code which I think fulfills your requirement.

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()

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM