How to access 'sender' for gestures in SwiftUI?

Viewed 236

I am laying out some cells in the style of a UICollectionView using the following code. The ImageUploadViewCell includes some logic to update the cell when its selected flag is toggled between true and false.

I can't figure out how to access the 'sender' view. I'm new to SwiftUI but have done a lot of iOS in the past. Am I thinking incorrectly about the design pattern? Should my cell's datasource be an ObservableObject and carrying around all the data to render the cell?

Note that dataStore is an @EnvironmentObject

LazyVGrid(columns: columns, alignment: .center, spacing: 7) {
    ForEach(dataStore.images.data.indices, id: \.self) { index in
            ImageUploadViewCell(url: dataStore.images.data[index].thumbnail)
                .aspectRatio(1, contentMode:.fill)
                .frame(width: cellSize, height: cellSize)
                .border(Color(UIColor.systemGray), width: self.selectMode ? 5 : 0)
                .clipped()
                .gesture(
                    TapGesture()
                        .onEnded { _ in

                            sender.selected.toggle() <--------- how do I do this?
                          
                            self.selectedItems.append(index)
                            print(dataStore.images.data[index])
                            print(self.selectedItems)
                        }
                )
    }
}
1 Answers

There is no sender. You should manage it by-data, not by-view, like

ForEach(dataStore.images.data.indices, id: \.self) { index in
        ImageUploadViewCell(url: dataStore.images.data[index].thumbnail)
            .aspectRatio(1, contentMode:.fill)
            .frame(width: cellSize, height: cellSize)
            .border(Color(UIColor.systemGray), 
                width: self.selectedItems.container(index) ? 5 : 0)  // << example !!
            .clipped()
            .gesture(
                TapGesture()
                    .onEnded { _ in
                        if self.selectedItems.contains(index) {
                           self.selectedItems.removeAll { $0 == index }
                        } else {
                           self.selectedItems.append(index)
                        }
                        print(dataStore.images.data[index])
                        print(self.selectedItems)
                    }
            )
}

If same is needed inside ImageUploadViewCell then you need to pass some model or binding to model inside, but change that model inside gesture handler.

Related