好吧,我对这里的集合视图以及它们如何连续实例化单元格缺乏理解。我正在将MsStickerViews以及该视图的本地描述(名称)添加到我的集合视图中。理想情况下,我只想这样做一次(不是每次用户滚动)。据我所知,标准的集合视图函数
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个单元格。
bool和存储已用名称的数组已经有所帮助,现在它们不会重叠,但最后一项永远不会添加。它不会放入used up names数组中。当我滚动时,单元格中的贴纸会移动,这意味着当我滚动到底部时,顶部的贴纸将位于底部。
我检查并创建了正确数量的单元格:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("COUNT",self.animalsAnim.count)
return self.animalsAnim.count
}我不知道这是什么原因。我怎样才能停止这种对单元的持续刷新?为什么我的字符串数组中的最后一项不能添加?怎么啦?
发布于 2017-03-11 07:02:49
使用不同的/更好的方法。
在情节提要中创建单元格模板。将模板中单元格的类设置为您的自定义类。将需要的字段添加到单元格中,并使用插座将它们连接到单元格。然后去掉所有向单元格添加自定义字段的代码。只需将值安装到cellForItemAt方法中已添加的单元格字段中即可。
发布于 2017-03-11 05:53:11
啊,算了。这是可行的:
override func prepareForReuse() {
super.prepareForReuse()
for view in self.subviews{
view.removeFromSuperview()
}
}https://stackoverflow.com/questions/42728156
复制相似问题