我有一个 collectionview 单元格,上面有一个图像,下面有一个按钮。现在,当我单击此按钮时,我想加载一个 tableviewCell
,其中包含来自 collectionview 的图像。为了实现这一目标,我最初这样做了..
func SellBtnTapped(_ sender: UIButton) {
let indexPath = collectionView?.indexPath(for: ((sender.superview?.superview) as! RecipeCollectionViewCell))
self.photoThumbnail.image = self.arrayOfURLImages[(indexPath?.row)!]
和 photoThumbnail
是这样定义的...var photoThumbnail: UIImageView!
但这样做会导致崩溃,告诉 'Unexpectedly found nil while unwrapping an optional value '
所以我尝试了这个..
let point = sender.convert(CGPoint.zero, to: self.collectionView)
let myIndexPath = self.collectionView.indexPathForItem(at: point)
self.photoThumbnail.image = self.arrayOfURLImages[(myIndexPath?.row)!]
但是,同样的 Unexpectedly found nil....
崩溃正在发生。关于可能是什么问题的任何想法......?
编辑:
这是 cellForItemAtIndex...
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath as IndexPath) as! RecipeCollectionViewCell
cell.sellButton.tag = indexPath.item
cell.sellButton.addTarget(self,action: #selector(SellBtnTapped(_:)),for: .touchUpInside)
return cell
}
最佳答案
这是因为您的 indexPath 总是nil
。
另一种方法是
在 collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath
方法中
设置标签你的单元格按钮,如
cell.myButton.tag = indexPath.item
在 SellBtnTapped
方法中使用下面的代码获取 indexPath
let indexPath = NSIndexPath(item: sender.tag, section: 0) // set section as you want
let cell = collectionView.cellForItem(at: indexPath as NSIndexPath) as! RecipeCollectionViewCell
现在,通过使用 cell,您可以获取其上的图像对象或使用 self.arrayOfURLImages
获取正确的图像。并做你进一步的事情。
关于ios - 在 Collection View 中访问 indexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46743205/