UICollectionView 单元格间距相等

UICollectionView equal cell spacing

我在集合视图中显示多张图片。它们都是相同的方向(横向),除了一个是纵向(见下图):

我正在尝试使肖像图像更居中,以便所有内容都均匀分布。关于如何做到这一点的任何想法?

PhotoGalleryViewController.swift:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoGalleryCell

    let image = UIImage(named: images[indexPath.row])
    cell.imageView.image = image
    cell.captionLabel.text = captions[indexPath.row]
    return cell
}

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    var size = CGSize()

    if (indexPath.row == 3)
    {
        size = CGSize(width: 450, height: 600)
    }
    else {
        size = CGSize(width: 940, height: 600)

    }
    return size
}

我的建议是不要根据肖像图像将在项目 3 中的事实更改单元格大小。

而是更新单元格的布局,以便无论将其分配给图像视图的图像如何,它都会将图像本身居中并将标签集中在图像下方。

在 ViewDidLoad 方法中放入此代码:

  let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
  layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
  layout.minimumInteritemSpacing = 0
  layout.minimumLineSpacing = 0
  collectionview.collectionViewLayout = layout

还将此添加到 cellForRow 方法中:

cell.imageview.contentmode = .aspectfit 

希望对解决您的问题有所帮助。