在collectionView swift 3

时间:2017-01-20 15:08:53

标签: swift image scroll uicollectionview

我在Swift 3中遇到了我的collectionView问题。我在Stackoverflow上找到了一些提示,尝试了它们,但是唉也无济于事。许多人提到使用'prepareReuse'方法,但我无法在我的代码中使用它们。向下滚动并再次备份后,图像已更改。所有图像都是字母表的字母。所以A,B,C是出现在视图顶部的第一批图像。如果你向下滚动并备份,一些随机的其他字母就取代了它们。我的整个代码如下:

import UIKit

class colViewController2: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

var imageData: [String] = [String]()
var imageCounter: Int = 0
var userHasHieroglyph: NSArray = ["","","C","D","E","F","G","H","I","J","K","L","M","N","O","","Q","R","S","T","U","V","W","X","Y","Z"]

override func viewDidLoad() {
    super.viewDidLoad()

    imageData = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    for b in imageData {
        if userHasHieroglyph.contains(b) {
            let newHieroglyph = b.lowercased()
            imageData[imageData.index(of: b)!] = "h-"+newHieroglyph
        }
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellid", for: indexPath) as! MyImageCell
    cell.backgroundColor = UIColor.white
    var currImage:String = ""
    currImage = self.imageData[self.imageCounter]
    self.imageCounter += 1

    if self.imageCounter >= self.imageData.count {
        self.imageCounter = 0
    }

    cell.image.image = UIImage(named: currImage)
    return cell
}

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 26
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 90, height: 90)
}
}

我希望我缺少一些代码来解决这个问题,但是经过Stackoverflow和互联网搜索了好几个小时后,我仍然无法找到解决这个问题的方法。如果有人有解决方案或提示,我们将不胜感激!

问候

1 个答案:

答案 0 :(得分:1)

问题在于您使用imageCounter作为图像数组的索引,但是增加它而不是使用indexPath.item。请记住,UICollectionView将重用UICollectionViewCell实例。基本上,它只会为屏幕上的那些创建单元格实例。如果一个单元格滚动离开屏幕并且新的单元格取代它(例如,如果你在屏幕上有" A"," B"和" C"并向下滚动,以便您看到" B"," C"," D",UICollectionView将重用" A"单元格用于&# 34; D"。这有点过于简单化,但或多或​​少都是如此有效)。因此,cellForItem调用将为您提供有关indexPath参数中显示的单元格的信息。在这种情况下,您可以删除所有self.imageCounter逻辑,而不是cell.image.image = UIImage(named: imageData[indexPath.row])

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellid", for: indexPath) as! MyImageCell
    cell.backgroundColor = UIColor.white
    cell.image.image = UIImage(named: imageData[indexPath.row])
    return cell
}