我制作了一个收集视图,以网格格式显示图像。代码如下:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var myCollectionView: UICollectionView!
let array:[String] = ["1", "2", "3"]
override func viewDidLoad() {
super.viewDidLoad()
let itemSize = UIScreen.main.bounds.width/3 - 3
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: itemSize, height: itemSize + 100)
layout.minimumInteritemSpacing = 3
layout.minimumLineSpacing = 3
myCollectionView.collectionViewLayout = layout
}
//Number of views
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array.count
}
//Populate view
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCell
cell.myImageView.image = UIImage(named: array[indexPath.row] + ".jpg")
return cell
}
现在,这样显示单元格...
为此,我在上述给定代码行的末尾添加了此代码块...
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if array.count == 3 {
if array[indexPath.row] == "1" {
return CGSize(width: 100, height: 200)
}
if array[indexPath.row] == "2" {
return CGSize(width: 100, height: 100)
}
if array[indexPath.row] == "3" {
return CGSize(width: 100, height: 100)
}
}
return CGSize(width: 100, height: 100)
}
但是这样会显示图像...
我在这里做错什么了?还有更好的方法吗??
编辑1:如果有5张图片,则显示为...