我在集合视图中显示多个图像。它们都是相同的方向(风景),除了一个,它是肖像(见下图):
我正在尝试使肖像图像更加居中,以便所有内容均匀分布。关于如何做到这一点的任何想法?
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
}
答案 0 :(得分:1)
我建议不要根据肖像图像在第3项中的事实来改变单元格大小。
而是更新单元格的布局,以便将其分配给它的图像视图的任何图像,它将使图像居中并将图像集中在图像下方。
答案 1 :(得分:0)
在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
希望有助于解决您的问题。