【问题标题】:Current Index associating with wrong data当前索引与错误数据相关联
【发布时间】:2016-09-26 18:47:17
【问题描述】:

我有一个水平滚动的集合视图,每个单元格都会在点击时推送到详细视图。当我加载应用程序时,我让它在索引处打印对象。首先,它会加载它应该加载的一个单元格。但是,当我滚动一个空格时,它会打印出两个新的 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)

    }

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

【问题讨论】:

    标签: ios swift didselectrowatindexpath nsindexpath


    【解决方案1】:

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

    【讨论】:

    • 那我该怎么做呢?我是否在尝试定义 currentIndex 的正确轨道上?
    【解决方案2】:

    EventDetailViewController 是我假设的 UICollectionViewController 子类。

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

    • 一种告诉集合数据源中有多少项的方法。 //1 覆盖 func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 // 你只有 1 个部分 }

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

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

    -一种使用其数据源填充单元格的方法。

    关注tutorial,我从中提取了部分代码,它们非常清楚地传达了这些核心概念。

    根据Apple's docs 的规定,重用发生在 UIKit 决定的许多单元格上,当您向上滚动一点 2 或 N 个单元格时,可以将其排入队列以进行重用。

    总之,通过这三种方法,您可以抵消您的收藏,从而跳过您想要避免的一条记录。

    编码愉快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-17
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多