UICollectionView spacing margins

后端 未结 15 1036
一向
一向 2020-11-30 16:58

I have a UICollectionView which shows photos. I have created the collectionview using UICollectionViewFlowLayout. It works good but I would like to

15条回答
  •  盖世英雄少女心
    2020-11-30 17:26

    Swift 4

        let flow = collectionView.collectionViewLayout as! UICollectionViewFlowLayout 
        // If you create collectionView programmatically then just create this flow by UICollectionViewFlowLayout() and init a collectionView by this flow.
    
        let itemSpacing: CGFloat = 3
        let itemsInOneLine: CGFloat = 3
        flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    
        //collectionView.frame.width is the same as  UIScreen.main.bounds.size.width here.
        let width = UIScreen.main.bounds.size.width - itemSpacing * CGFloat(itemsInOneLine - 1) 
        flow.itemSize = CGSize(width: floor(width/itemsInOneLine), height: width/itemsInOneLine)
        flow.minimumInteritemSpacing = 3
        flow.minimumLineSpacing = itemSpacing
    

    EDIT

    XCode 11.4 and swift 5

    let flow = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    

    doesn't work. Use below works.

    let flow = UICollectionViewFlowLayout()

    and after configuration:

    collectionView.collectionViewLayout = flow

    And if you want to change to scrollDirction horizontally:

    flow.scrollDirection = .horizontal

    NOTE

    If you set items in one lines isn't correctly, check if your collection view has paddings. That is:

    let width = UIScreen.main.bounds.size.width - itemSpacing * CGFloat(itemsInOneLine - 1)

    should be the collectionView width.

提交回复
热议问题