ios - 在 Collection View 中访问 indexPath

标签 ios swift uicollectionview

我有一个 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/

相关文章:

ios - 如何使用 AFNetworking 2.0 为请求设置全局参数?

ios - 隐藏 iOS 导航栏中的所有内容,包括图标

ios - Swift - 应用程序中的慢动作相机

ios - 为什么 UITableViewCell 有一个 contentView 属性?

ios - 如何在滚动 Swift 时设置 UICollectionView 层不移动/静态

ios - 禁用 UIPageViewController 反弹

ios - 在 Tableview Swift 中删除 Header View Section 的白色边框底部

ios - 谓词不适用于 NSSet

ios - 当我没有引用时,如何使用/编辑导航栏功能?

ios - 防止 UICollectionView 崩溃