当我快速滚动它时,图像在集合视图中发生变化

时间:2016-05-06 00:47:15

标签: xcode swift

当我快速滚动它时,图像在collectionView中发生了变化

滚动图像更改时我该怎么办?

来自json的数据:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    let cell: CollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell
    let mindata = (data[indexPath.row] as! NSDictionary)
    cell.NameShow!.text = mindata["name"] as? String
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    {
        if let url  = NSURL(string: (mindata["img"] as? String)!),
        data = NSData(contentsOfURL: url)
        {
            dispatch_async(dispatch_get_main_queue(),
            {
                cell.img.image = UIImage(data: data)
            })
        }
    })
}

1 个答案:

答案 0 :(得分:1)

你的代码不满,所以我可以提出一些提示:

UITableView和UICollectionView都使用重用技术,这意味着一旦创建了单元格,就会从池中重用它们。

鉴于您所说的问题,看起来您没有清理您的手机,无法将图像绑定到特定位置。

您可以根据自己的需要尝试:

  1. 子类UICollectionViewCell,在prepareReuse中,您清理图像,因此清理单元格,如果您不关心订单,可以提供您喜欢的任何图像。

  2. 将图像与单元格indexPath绑定,这意味着您可以使用某种索引创建图像数组或标记图像。

  3. 例如cellForItemAtIndexPath

    func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        ...
        cell.img.image = imageArray[indexPath.row]
        ...
    }