Gestures |

This is a companion discussion topic for the original entry at
1 Like

Drawing in iOS with Swift
Part 1: Video 9 - Gestures
In the very first portion of the video, we code a tap gesture:
.onTapGesture {
self.cellData.selectedCell = self.cell
I do not understand how the tap identifies the cell. I see no arguments passed in. I see no setting anywhere. It seems like magic that CellView’s cell property knows what cell is selected. Please enlighten me. Thanks!

You’re adding the code to CellView. There is only one cell per CellView, so self.cell identifies the cell tapped.

When you test it on BackgroundView, there are two CellViews. Each CellView identifies its own cell.

Does that make sense?

However, I would agree with you, that there’s so little code it does seem like magic.

1 Like

Well, I certainly understand that Background view contains multiple instances of CellView, and that each CellView contains an instance of Cell. I was missing the link in terms of Cell instances. Looking at this again with fresh eyes, I see what I missed: cell is instantiated and passed into the CellView() preview constructor, or, in the case of BackGroundView, its preview constructor gets an instance of CellData, which has the two Cell instances we hard-coded. Got it. Thanks for your response. :blush:

1 Like

Some great stuff in here @caroline! Thank you so much. One way I discovered to make things look a little bit more “pretty” is to package the gesture into a property:

  var doubleTap: some Gesture {
    TapGesture(count: 2)
      .sequenced(before: DragGesture(minimumDistance: 0))
      .onEnded { value in
        switch value {
        case .second((), let drag):
          if let drag = drag {
            print("add new cell at: ", drag.location)
            self.newCell(location: drag.location)

You need to use some Gesture because the actual type gets quite complicated. This way the body can be made simpler and even drop the return keyword. :]

1 Like

That’s a good one. Thanks Ray!

@rayfix Thank you for sharing your solution - much appreciated! :]