【问题标题】:How to access 'sender' for gestures in SwiftUI?如何在 SwiftUI 中访问“发送者”的手势?
【发布时间】:2020-09-23 18:14:59
【问题描述】:

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

我不知道如何访问“发件人”视图。我是 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)
                        }
                )
    }
}

【问题讨论】:

    标签: ios swiftui


    【解决方案1】:

    没有发件人。你应该按数据而不是按视图来管理它,比如

    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 内部也需要相同,那么您需要将一些模型或绑定传递给内部模型,但在手势处理程序中更改该模型。

    【讨论】:

    • 我明白你在说什么,但我需要一个 ViewModel 数组,每个单元格一个,对吧?如何将此数组初始化为与我的数据源相同的大小?我的数据源是一个未知大小的@EnvironmentObject
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2019-10-24
    相关资源
    最近更新 更多