【发布时间】:2019-04-26 11:00:21
【问题描述】:
我在 cellForItemAtIndexPath 中遇到问题,我将图像设置为单元格的 UIButton,但每次滚动 collectionView 的单元格时,它都会一次又一次地将图像放置在已设置的图像之上。我可以说是因为图像的阴影越来越厚。我正在从该快速文件中创建的图像文字数组中提取图像,并且正在加载正确的图像,因此那里没有问题。我确信这对大多数人来说是一个简单的解决方法,但我似乎无法在任何地方找到答案。
Image of my cellForItemAtIndexPath function
My app running before I scroll
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! HomeViewCell
collectionView.bounces = false
let imageNumber = indexPath.item
let collectionImage: UIButton = {
let image = UIButton()
image.setImage(collectionImageArray[imageNumber].withRenderingMode(.alwaysOriginal), for: .normal)
image.contentMode = .scaleAspectFit
image.addTarget(self, action: #selector(handleCollectionTap), for: .touchUpInside)
return image
}()
collectionImage.imageView?.image = collectionImageArray[imageNumber]
cell.addSubview(collectionImage)
collectionImage.anchor(top: nil, left: nil, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
collectionImage.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true
collectionImage.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
print(imageNumber)
return cell
}
【问题讨论】:
-
这是预期的行为:单元被重用(...dequeueReusableCell...)。检查子视图是否已经存在或在 Interface Builder 中设计按钮。
-
@vadian 我只在单元格中为索引路径方法添加了一次子视图。它不会不断添加该子视图吗?至于界面构建器,我更喜欢用代码来完成。
-
再次重复使用单元格。有一个单元池,其中包含尽可能多的单元格(加上 1 或 2 个)以适合表格视图。因此,如果一个单元格离开屏幕,则该单元格将以其离开屏幕的状态放入池中。下次需要一个新单元时,框架会从单元池中取出一个。此单元格已有自定义按钮。
标签: uicollectionview swift4 uicollectionviewcell xcode9