如何解决没有将UIImage添加到UICollectionView中的所有单元格
我为每个单元格添加了collection view
,并添加了image view
。我能够为每个单元添加和缩放图像视图,但是它们稍微偏离中心。我将图像视图的中心设置为单元格的中心,但这导致现在只显示一张图像。
代码如下:
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CarCell",for: indexPath)
let carImageView = UIImageView(image: UIImage(systemName: "car"))
carImageView.frame = cell.contentView.frame
carImageView.center = cell.center
carImageView.contentMode = .scaleAspectFit
cell.addSubview(carImageView)
return cell
}
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeforItemAt indexPath: IndexPath) -> CGSize {
let columns: CGFloat = 2
let collectionViewWidth = collectionView.bounds.width
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let spaceBetweenCells = flowLayout.minimumInteritemSpacing * (columns - 1)
let adjustedWidth = collectionViewWidth - spaceBetweenCells
let width: CGFloat = floor(adjustedWidth / columns)
let height: CGFloat = width
return CGSize(width: width,height: height)
}
这是结果:
视图层次结构显示所有单元格都是用其UIViews
创建的,而不是image views
:
删除carImageView.center = cell.center
行会使所有图像再次出现,但偏心。有人知道如何解决这个问题吗?
解决方法
您可以尝试以下方法吗?
let carImageView = UIImageView(image: UIImage(systemName: "car"))
carImageView.frame = cell.contentView.bounds
carImageView.center = CGPoint(x: cell.bounds.width/2,y: cell.bounds.height/2)
carImageView.contentMode = .scaleAspectFit
cell.addSubview(carImageView)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。