当前索引与错误数据相关联

时间:2016-09-26 18:47:18

标签: ios swift didselectrowatindexpath nsindexpath

我有一个水平滚动的集合视图,每个单元格在点击时推送到详细视图。当我加载应用程序时,我让它在索引处打印对象。首先,它将加载它应该的一个单元格。但是当我滚动一个空格时,它打印出两个新的ID,然后开始将最后一个加载的单元格的数据与当前屏幕上的数据相关联,现在关闭一个点。我不知道如何解决这个问题,我最好的猜测是有一些方法可以更好地跟上当前的索引,或者在viewDidAppear中有一些东西可能是我遗漏了。这是一些代码:

open var currentIndex: Int {
    guard (self.collectionView) != nil else { return 0 }

    return Int()
}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExpandCell", for: indexPath) as! ExpandingCollectionViewCell

    let object = self.imageFilesArray[(indexPath).row]  as! PFObject
    cell.nameLabel.text = object["Name"] as! String
    whatObject = String(describing: object.objectId)
    print(whatObject)
    return cell
    }


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {


    let object = self.imageFilesArray[(indexPath as NSIndexPath).row]

    guard let cell = collectionView.cellForItem(at: indexPath) as? ExpandingCollectionViewCell else { return }

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "EventDetailViewController") as! EventDetailViewController
        nextViewController.lblName = nameData
        nextViewController.whatObj = self.whatObject
        self.present(nextViewController, animated:false, completion:nil)

    }

有没有人知道设置当前索引的更好方法,所以我总是将正确的数据推送到下一页?

2 个答案:

答案 0 :(得分:0)

设置单元格元素的数据源可以保留索引的计数,该索引也可以设置为属性,并可用于从单元格中检索以获取正确的当前索引。

答案 1 :(得分:0)

EventDetailViewController是我假设的UICollectionViewController子类。

如果这是正确的,那么你需要实现它:

  • 一种方法,用于告知集合数据源中有多少项。 // 1 override func numberOfSections(在collectionView:UICollectionView中) - > Int { return 1 //你只有1个部分 }

    // 2 override func collectionView(_ collectionView:UICollectionView,                            numberOfItemsInSection section:Int) - > Int { return array.count //这是你必须显示的模型数量......它们都将存在于一个部分中 }

  • 一种方法,告诉集合哪个cellView子类用于该给定行。

- 使用它的数据源填充单元格的方法。

按照我提取部分代码的tutorial,他们非常清楚地传达了这些核心概念。

根据Apple's docs重复使用UIKit决定的多个单元格,当你向上滚动一点点时,或者N个单元格可以被重新使用。

总之,使用这三种方法,您可以将您的集合偏移到跳过您想要避免的一条记录。

快乐的编码!