[英]Displaying three cells in collection view
我制作了一個集合視圖,以網格格式顯示圖像。 代碼如下:
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張圖片,則顯示為...
您需要按照以下鏈接中的描述創建自定義布局。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.