好的,我对这里的集合视图缺乏理解,以及它们如何不断实例化单元。我将MsStickerViews与该视图的本地描述(名称)一起添加到我的集合视图中。理想情况下,我只想这样做一次(不是每次用户滚动)。根据我的理解,标准收藏查看功能Swift集合视图不会添加超过6个项目?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
每当用户滚动并且会;只要不断添加你一次又一次地放入这个函数。为了解决这个问题,我创建一个单独的类StickerCollectionViewCell
在那里我有这些初始化函数:
public var animalName = String()
var logoLabel = UILabel()
public var hasSticker = Bool(false)
public func initSticker(stickerView: MSStickerView)
{
print("PUTTING: ",stickerView.sticker?.localizedDescription)
self.addSubview(stickerView)
stickerView.startAnimating()
}
public func initLabels()
{
//print("called", animalName)
logoLabel.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 100)
logoLabel.textColor = UIColor.black
logoLabel.textAlignment = .center
//logoLabel.text = stickerPack[indexPath.item].sticker?.localizedDescription.uppercased()
logoLabel.text = animalName.uppercased()
logoLabel.font = UIFont(name: "Futura-Bold", size: screenSize.height * (9.8/screenSize.height))
logoLabel.center = CGPoint(x: self.bounds.width * 0.5, y: self.bounds.height * 0.96)
self.addSubview(logoLabel)
}
我再加入我的细胞是这样的:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "stickerCell", for: indexPath as IndexPath) as! StickerCollectionViewCell
cell.backgroundColor = UIColor.clear// make cell more visible in our example project
if(cell.hasSticker == false && animalNames.contains((stickerPack[indexPath.item].sticker?.localizedDescription)!) == false)
{
cell.initSticker(stickerView: stickerPack[indexPath.item])
cell.animalName = (stickerPack[indexPath.item].sticker?.localizedDescription)!
cell.initLabels()
animalNames.append(cell.animalName)
cell.hasSticker = true;
}
print("Animal names", animalNames)
return cell
}
的原因if语句我加入我的从一个名称数组贴图视图,直到今天我只有6个名字在数组中。现在用7,它开始将数组中的最后一项添加到另一个单元格的顶部,即使我计算了它,它仍然会生成7个单元格。
布尔和存储已用完的名称数组已帮助他们现在不会重叠,但最后一个项目永远不会被添加。它不会放入用过的名称数组中。当我滚动时,单元格中的贴纸会左右移动,这意味着当我滚动到底部时,顶部的贴纸将位于底部。
我检查,我创建单元格的右边数:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("COUNT",self.animalsAnim.count)
return self.animalsAnim.count
}
我不知道是什么原因造成这一点。我怎样才能阻止细胞持续的清新?为什么我的字符串数组中的最后一项不会被添加?哪里不对?
你不想要'if'语句。随着collectionview滚动,每当需要一个单元时,都会调用celForRowAt。您可以使先前使用的单元对象出队。你的代码需要根据indexpath – Paulw11