如何在SwiftUI中访问手势的“发送者”?

时间:2020-09-23 18:14:59

标签: ios swiftui

我正在使用以下代码以UICollectionView样式布置一些单元格。 ImageUploadViewCell包含一些逻辑,用于在其selected标志在true和false之间切换时更新单元格。

我不知道如何访问“发件人”视图。我是SwiftUI的新手,但过去做过很多iOS。我是否对设计模式有误?我的单元格的数据源应该是一个ObservableObject并携带所有数据以呈现该单元格吗?

请注意,dataStore是@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 个答案:

答案 0 :(得分:2)

没有发件人。您应该按数据而不是按视图进行管理,例如

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)
                    }
            )
}

如果在ImageUploadViewCell内部需要相同的内容,则需要在内部传递一些模型或绑定到模型,但是在手势处理程序内部更改该模型。