swift中gridLayout的问题

时间:2018-03-19 23:34:50

标签: ios swift user-interface

所以我有这些委托方法来帮助我布局我的collectionView。我试图创建一些网格布局,其中有X numberOfSections和X numberOfItemsInSection。根据我现在所拥有的内容,它将所有权利放在一起,并将它们隔开太远,以至于单元格转到下一行的位置。如何在一行中为一个部分拟合所有单元格。

 //Asks the delegate for the size of the header view in the specified section.
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return .zero
    }
    //Asks the delegate for the size of the footer view in the specified section.
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return .zero
    }
    //Asks the delegate for the size of the specified item’s cell.
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (collectionView.bounds.size.width - CGFloat(numberOfItemsInSection))/2.2, height: collectionView.bounds.size.height - 50)

    }
    //Asks the delegate for the margins to apply to content in the specified section.
    //in short in controls the amount of space between the items above,left,right, and below
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
    }
    //Asks the delegate for the spacing between successive rows or columns of a section.
    //controls the space in between rows and columns
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }
    //Asks the delegate for the spacing between successive items of a single row or column.
    //controls the space between each cell
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }

我觉得它与sizeForItemAt有关但我无法弄清楚如何更改它。

这就是它目前的样子。

enter image description here

1 个答案:

答案 0 :(得分:0)

您是对的,它与sizeForItemAt方法有关,您应该使用indexPath参数,以便您可以使用其属性section来定义每个项目的大小部分。

请记住,项目之间有一个空格,因此在计算宽度和高度时需要考虑到这一点,因此您可以使用minimumLineSpacingForSectionAtminimumInteritemSpacingForSectionAt方法调整间距。

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

    if indexPath.section == 0 {
        return CGSize(width: 200, height: 100)
    }

    return CGSize(width: (collectionView.bounds.size.width - CGFloat(numberOfItemsInSection))/2.2, height: collectionView.bounds.size.height - 50)

}