首页 > 解决方案 > swift 4在同一个UICollectionView垂直流上设置不同高度和宽度的单元格

问题描述

我正在尝试制作如下图所示的图像网格 在此处输入图像描述

我尝试了下面的代码

import UIKit
class ViewController: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource  {
@IBOutlet weak var collectionViw: UICollectionView!

var widthss = [59.0,59.0,59.0,121.0,59.0,59.0,59.0,59.0,59.0,59.0,28.0,28.0,59.0,59.0,] as [CGFloat]
var heights = [36.0,36.0,36.0,76.0,36.0,76.0,36.0,36.0,36.0,76.0,36.0,36.0,36.0,76.0,] as [CGFloat]
override func viewDidLoad() {
    super.viewDidLoad()

}
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return heights.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICustomCollectionViewCell
    // Customize cell height
    cell.frame = CGRect(x: cell.frame.origin.x, y: cell.frame.origin.y , width: widthss[indexPath.row], height: heights[indexPath.row])

    return cell
    }




}
extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {


    return CGSize(width: widthss[indexPath.row], height: heights[indexPath.row])
}
func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout
    collectionViewLayout: UICollectionViewLayout,
                    minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 1.0
}}

最后,我找到了如下图所示的结果, 在此处输入图像描述

我需要的是使集合视图单元格像第一张图片任何人都知道我的错误在哪里提前谢谢

标签: iosswift

解决方案


推荐阅读