【问题标题】:Swift - UICollectionView repeats (duplicate) cellsSwift - UICollectionView 重复(重复)单元格
【发布时间】:2014-11-04 11:29:22
【问题描述】:

您好,我有一个数组,其中包含从 flickr 获取的 100 张图片 url。当我使用 UICollectionView 时,我显示 100 个单元格,屏幕上只有 8 个单元格,当我向下滚动查看下一个 8 个时,它们与上一个相同,当我执行时

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

和 println("something") 它只在控制台中写入 8 次,但数组的内容是 100

我用这个:

func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int {
    return self.photosUrls.count
}

它会产生 100 个细胞,但细胞总是重复...任何知道如何在新版本的 XCode GM 种子中击败 Swift 的人?

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {
    let cell: ImageCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as ImageCell
    let imgUrl = photosUrls[indexPath!.row]
    let api_url = NSURL.URLWithString(imgUrl)
    let URLReq = NSURLRequest(URL: api_url)
    let NSOpQ:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(URLReq, queue: NSOpQ, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        if(error == nil){
            cell.theWPImage!.image = UIImage(data: data)
        }
        })
    return cell
}

【问题讨论】:

    标签: swift duplicates uicollectionview cells


    【解决方案1】:

    您的问题是您试图在 cellForRow 函数中加载图像。到下载图像时,您的 collectionView 正在显示另一个单元格。 正确的方法之一是将 viewDidLoad 中的图像加载到数组中,然后从 cellForRow 中的该数组加载。

    【讨论】:

      【解决方案2】:

      我认为您不了解 UITableViewUICollectionView 委托方法的工作原理。

      iOS 不会同时加载 100 个单元,因为它会非常慢并且用户体验不好。因此,方法cellForItemAtIndexPathcellForRowAtIndexPath 仅在单元格出现在屏幕上时被调用。

      每当您向下滚动时,您都会看到再次调用 cellForItemAtIndexPath 方法来创建新单元格。如果您将代码println(indexPath.row) 放入cellForItemAtIndexPath 中,实际上您会在向上或向下滚动时看到重复打印单元格编号。

      如果您在向下滚动后看到相同的单元格,可能是由于您在 cellForItemAtIndexPath 上的代码。除非您粘贴上面的完整源代码,否则我无法为您提供帮助。或者它可能是 XCode GM 种子的 UICollectionView 中的一个错误。

      在 XCode 6 Beta 7 中尝试相同的项目并报告回来怎么样?我在 XCode GM 中也遇到了 UICollectionView 的问题。 IT 与约束有关。请参阅:iOS 8 GM does not update constraints on collection views 因此,我现在正在使用 XCode 6 Beta 7。

      【讨论】: