簡體   English   中英

如何使用 onTapGesture 更改視圖的偏移量?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM