Swift 3 collection查看如何设置间距。

时间:2018-04-26 23:18:10

标签: swift swift3 collections view

enter image description here

  1. 你如何将3个细胞集中在一起?它在左边。

  2. 如何在每个单元格的所有边上设置相同的间距?

  3. 第二个单元格,表示未找到任何结果。你会如何让它居中并占据整个屏幕?现在它在左上角切断了。

2 个答案:

答案 0 :(得分:2)

您需要使用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

enter image description here

输出:

enter image description here

答案 1 :(得分:0)

你也可以这样使用:

    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()

<强>输出:

enter image description here

希望这有帮助。