从一个视图拖放到另一个视图,然后进行更改更新

时间:2020-06-02 20:56:30

标签: swiftui

用户的视图包含一副纸牌(父母)。 用户可以将卡拖到存储桶(子级)中

我是新手,一般来说很快。我在如何移动所选的一张卡并将其附加到孩子方面遇到麻烦。另外,关于子项的更新适用于本地组件,而不适用于整个应用程序,因为在一个应用程序中正在进行许多纸牌游戏。

父母:

struct ParentView: View {
    var cardViews: [CardView] = {
        var views = [CardView]()
        for index in 0..<5 {
            views.append(CardView(cardData: cardData[index], flipDeck: true))
        }
        return views
    }()

    var body: some View {
       VStack { 
          ZStack {
                ForEach(cardViews) { cardView in
                cardView
                .gesture(LongPressGesture(minimumDuration: 0.01)
                .onChanged({ (value) in // blah blah})
                .onEnded({ (value) in
                            guard case .second(true, let drag?) = value else { return }
                            if drag.translation.width < -self.dragAreaThreshold ||                                              drag.translation.width > self.dragAreaThreshold { 
                            self.moveCards() // ? move this into childView
                }})
       }

       ChildView(selectedCard: $selectedCard)
       .opacity(dragState.isDragging ? 0.0 : 1.0)
       .animation(.default)
    }    
}

 struct ChildView: View {

    @Binding var selectedCard: CardView // card from parent, how to append to [cardViews]?

    @State var showInfoView: Bool = false
    @State var cardViews: [CardView] = { // ?? how to get selectedCard in here??
        var views = [CardView]()
        for index in 0..<5 {
            views.append(CardView(cardData: cardData[index]))
        }
        return views
    }()

    let haptics = UINotificationFeedbackGenerator()

    var body: some View {

        HStack {
            ScrollView(.horizontal, content: {
                HStack(spacing: 10) {
                    ForEach(cardViews) { cardView in

                        cardView.onTapGesture(count: 2) {
                            self.selectedCard = self.findCard(cardView: cardView)[0]
                            self.cardViews = self.removeCard(cardView: cardView)
                        }
                        .transition(AnyTransition.opacity.combined(with: .offset(y: 50)))
                    }
                }
            })
        }
    }

    private func findCard(cardView: CardView) -> [CardView] {
        return cardViews.filter { $0.id == cardView.id }
    }

    private func removeCard(cardView: CardView) -> [CardView] {
        return cardViews.filter { $0.id != cardView.id }
    }

    private func addCards(_ card: CardView) { self.cardViews.append(card) }

    }

0 个答案:

没有答案