Добавление жеста перетаскивания к изображению внутри ForEach в SwiftUI - PullRequest
2 голосов
/ 19 апреля 2020

В настоящее время я разрабатываю приложение, показывающее пользователю его ящики с растениями и некоторые измерения (например, влажность почвы, температура и т. Д. c). В каждом ящике с растениями есть несколько растений, которые отображаются в подробном представлении. Я хочу, чтобы пользователь мог перетащить одно из растений в угол, чтобы удалить его. В настоящее время у меня есть эта реализация:

@GestureState private var dragOffset = CGSize.zero

var body: some View {

    //Plants Headline
    VStack (spacing: 5) {
        Text("Plants")
            .font(.headline)
            .fontWeight(.light)

        //HStack for Plants Images
        HStack (spacing: 10) {

            //For each that loops through all of the plants inside the plant box
            ForEach(plantBoxViewModel.plants) { plant in

                //Image of the individual plant (obtained via http request to the backend)
                Image(base64String: plant.picture)
                    .resizable()
                    .clipShape(Circle())
                    .overlay(Circle().stroke(Color.white, lineWidth: 2))
                    .offset(x: self.dragOffset.width, y: self.dragOffset.height)
                    .animation(.easeInOut)
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 70, height: 70)
                    .gesture(
                           DragGesture()
                            .updating(self.$dragOffset, body: { (value, state, transaction) in
                               state = value.translation
                           })
                   )
            }
        }
    }

}

Это выглядит следующим образом: Скриншот фрагмента кода

Однако, когда я начинаю перетаскивать, оба изображения перемещаются. Я думаю, это потому, что смещение обоих изображений привязано к одной и той же переменной (DragOffset). Как я могу сделать так, чтобы sh только 1 изображение двигалось?

Я думал о реализации некоторого вида массива, который отображает индекс завода в заданное смещение c, но я не знаю, как внедрить его в жест. Спасибо за любую помощь!

1 Ответ

0 голосов
/ 19 апреля 2020

Здесь возможен подход - сохранить выделение во время перетаскивания. Протестировано с Xcode 11.4 / iOS 13.4.

demo

@GestureState private var dragOffset = CGSize.zero
@State private var selected: Plant? = nil // << your plant type here
var body: some View {

    //Plants Headline
    VStack (spacing: 5) {
        Text("Plants")
            .font(.headline)
            .fontWeight(.light)

        //HStack for Plants Images
        HStack (spacing: 10) {

            //For each that loops through all of the plants inside the plant box
            ForEach(plantBoxViewModel.plants) { plant in

                //Image of the individual plant (obtained via http request to the backend)
                Image(base64String: plant.picture)
                    .resizable()
                    .clipShape(Circle())
                    .overlay(Circle().stroke(Color.white, lineWidth: 2))
                    .offset(x: self.selected == plant ? self.dragOffset.width : 0,
                            y: self.selected == plant ? self.dragOffset.height : 0)
                    .animation(.easeInOut)
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 70, height: 70)
                    .gesture(
                        DragGesture()
                            .updating(self.$dragOffset, body: { (value, state, transaction) in
                                if nil == self.selected {
                                    self.selected = plant
                                }
                                state = value.translation
                            }).onEnded { _ in self.selected = nil }
                )
            }
        }
    }

}
...