简体   繁体   中英

Swift 3 collectionView how to set spacing.

在此处输入图片说明

  1. How do you center the 3 cells? Its to the left.

  2. How do you set same spacing on all sides of each cell?

  3. Second cell that says no results found. how would you make that centered and take up whole screen? Right now its cut off in the top left corner.

you need to make use of collectionView flowLayout

let width = UIScreen.main.bounds.size.width

//MARK:- Collection View Flow Layouts
extension HomeVC : UICollectionViewDelegateFlowLayout
{    
    //MARK: Setting size of cell
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: width/3-16, height: width/3-16)
    }

    //MARK: Setting space Around Corners of Cells
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return  UIEdgeInsetsMake(8, 8, 8, 8)
    }

    //MARK: Setting space between two sections
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {
        return 0
    }

    //MARK: Setting Space between two Cels
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
    {
        return 8
    }
}

StoryBoard Design

在此处输入图片说明

Output:

在此处输入图片说明

You can also use like this:

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    let width = UIScreen.main.bounds.size.width
    layout.itemSize = CGSize(width: width/3.05, height: width/3.05)
    layout.sectionInset = UIEdgeInsets(top: 2, left: 1, bottom: 2, right: 1)
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 2
    collectionView!.collectionViewLayout = layout
    collectionView.reloadData()

Output:

在此处输入图片说明

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM