UICollection查看自定义布局

时间:2018-03-20 09:37:32

标签: swift uicollectionview uicollectionviewlayout

我正在尝试布局一个UICollectionView,就像我在照片中绘制的模型一样(也显示了每个项目的索引)。

我对UICollectionViewLayout进行了一些研究,并且还实现了一些方法,但结果是什么

enter image description here

enter code here

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let padding: CGFloat =  50
        let collectionViewSize = collectionView.frame.size.width - padding
        if indexPath.row == 3{
            return CGSize(width: collectionViewSize, height: collectionViewSize/2)
        }
        else{
        return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
        }
    }

using above function i get result shown in image...but i not want 3rd number cell

1 个答案:

答案 0 :(得分:1)

尝试如下:

  1. 为班级顶部的边距声明CGFloat,并将其设置在viewDidLoad()中,如下所示:

    var margin: CGFloat!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // set your margin to whatever suits you
        margin = 2
    
    }
    
  2. 覆盖minimumInteritemSpacingForSection函数并将其设置为返回边距变量:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
         return margin
    }
    
  3. 覆盖sizeForItem函数,如下代码:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
        if indexPath.item < 3 {
           if indexPath.item > 0 && indexPath.item == 2 {
            return CGSize(width: view.frame.width, height: 100)
           } else {
    
              return CGSize(width: (collectionView.frame.width / 2) - margin, height: 100)
           }
        } else {
        if (indexPath.item + 1) % 3 == 0 {
            return CGSize(width: view.frame.width, height: 100)
        } else {
            return CGSize(width: (collectionView.frame.width / 2) - margin, height: 100)
        }
     }
    
    }
    
  4. 希望有所帮助:)