【问题标题】:Selecting UICollectionViewCell programmatically [closed]以编程方式选择 UICollectionViewCell [关闭]
【发布时间】:2024-05-21 01:45:01
【问题描述】:

问题 - 我正在尝试以编程方式选择 UICollectionView 单元格。我查看了 * 上提到的所有解决方案,但没有一个对我有用。这是我尝试过的

我尝试了什么 -

                for i in 0 ..< self.categories.count {
                    if (MUser.sharedInstance.recommendations.contains(self.categories[i].name)) {
                        let indexPath = IndexPath(item: i, section: 0)
                        self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .top)
                        self.collectionView(self.collectionView, didSelectItemAt: indexPath)
                    }
                }

【问题讨论】:

  • 什么不起作用?
  • 它不卖商品
  • 是什么导致您得出未选择项目的结论?

标签: ios swift xcode uicollectionview


【解决方案1】:

在 mainThread 上调用它们会起作用

DispatchQueue.main.async {
     let indexPath = IndexPath(item: i, section: 0)
     self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .top)
     self.collectionView(self.collectionView, didSelectItemAt: indexPath)
}

【讨论】:

  • 那也不行
【解决方案2】:

直接调用 didSelectItem 函数即可

collectionView(colletionView, didSelectItemAt: indexPath)

【讨论】:

  • 那行不通