如何在我的按钮功能中访问indexPath.item?

时间:2015-11-03 00:35:16

标签: ios swift

我有一个程序可以搜索数据库并填充集合视图。目前有效。每个项目都有一个“跟随”按钮,当单击该按钮时,我需要它来执行操作,但我需要该操作才能访问indexPath.item。程序崩溃的原因是因为按钮的功能隐藏在集合视图方法中,但这是我可以访问indexPath.item的唯一方法。如何修复崩溃并仍然可以访问indexPath.item

func followuser(sender: UIButton){
   let pointInTable: CGPoint = sender.convertPoint(sender.bounds.origin, toView: self.collectionview)
    if var indexPath :NSIndexPath = self.collectionview.indexPathForItemAtPoint(pointInTable){
        print(pointInTable)
    }
    var relation: PFRelation = (PFUser.currentUser()?.relationForKey("Friendship"))!
    //relation.addObject(users[indexPath.item])

    print(relation)
}


 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionview.dequeueReusableCellWithReuseIdentifier("searchcell", forIndexPath: indexPath) as! searchcustomcell

       cell.follow.addTarget(self, action: "followuser:", forControlEvents: UIControlEvents.TouchUpInside)

1 个答案:

答案 0 :(得分:1)

我不确定indexPath.item你的意思。 NSIndexPath没有属性item,因此除非您创建了NSIndexPath类别,否则代码可能无法正常运行。

我不知道你在哪里获得indexPath变量的价值。

你有几个挑战。第一个挑战是获取包含被点击按钮的单元格的indexPath。

您这样做的一种方法是使用UICollectionView方法indexPathForItemAtPoint。您可以使用按钮的边界并使用其中一种UIView方法在坐标系之间转换点,以将按钮的原点从它的坐标系转换为集合视图'坐标系。然后,您将获取转换后的坐标,并在调用indexPathForItemAtPoint时使用它来获取包含该按钮的indexPath。

下一个挑战:你想通过indexPath查找什么?

表视图和集合视图通常将模型数据存储在1维数组(对于单行项)或2维数组(对于单元格网格)中。

您需要获取索引路径并获取行或行和部分,并使用它来索引模型以获取您需要获取的任何内容。

但是,在您告诉我们您的集合视图的组织方式以及如何存储代表您的单元格数据的模型之前,我们无法为您提供帮助。