简体   繁体   English

UIImage 未添加到 UICollectionView 中的所有单元格

[英]UIImage not being added to all cells in UICollectionView

I have added a collection view and added an image view for each cell.我添加了一个collection view并为每个单元格添加了一个image view I was able to add and scale the image views for each cell, but they were slightly off centre.我能够为每个单元格添加和缩放图像视图,但它们稍微偏离了中心。 I set the image view's centre to the cell's centre, but this caused only one image to now show.我将图像视图的中心设置为单元格的中心,但这导致现在只显示一张图像。

Here is the code:这是代码:

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)
    
}

Here is the outcome:结果如下:

在此处输入图片说明

And the view hierarchy shows all cells are created with their UIViews , but not the image views :视图层次结构显示所有单元格都是用它们的UIViews创建的,但不是image views

在此处输入图片说明

Removing the line carImageView.center = cell.center makes all images reappear again, but off-centre.删除行carImageView.center = cell.center使所有图像再次重新出现,但偏离中心。 Does anyone know how to fix this?有谁知道如何解决这一问题?

Can you try with the following?您可以尝试以下方法吗?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM