简体   繁体   English

Swift:在添加项目时更改UICollectionView中单元格布局的宽度

[英]Swift: Change the width of cell Layout in UICollectionView when add items

I'm new to swift , i want to make a UICollectionViewCell layout to be dynamic example: if we have an item added to look like this: 我是swift的新手,我想将UICollectionViewCell布局设为动态示例:如果我们添加了一个看起来像这样的项目:

1.if we have one item it look like this 1.如果我们有一件物品看起来像这样

在此处输入图片说明

2.If we have two items added to look like this: 2.如果我们添加了两个项目,看起来像这样:

在此处输入图片说明

3. if we have item 3 again to look like this : 3.如果我们再次拥有第3项,则如下所示:

在此处输入图片说明 This process proceeds this way, as long as there are items 只要有项目,此过程就会以这种方式进行

Thanks! 谢谢!

This is method of UICollectionViewDelegateFlowLayout for the size of items. 这是用于项目大小的UICollectionViewDelegateFlowLayout的方法。 Just check for total item count odd/even and based on that decide you cell width. 只需检查总项目数为奇/偶,然后根据此决定您的单元格宽度即可。

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

    if arrList.count % 2 == 0 {

        let width = (collectionView.frame.width-20)/2
        let height : CGFloat = 100.0
        return CGSize(width: width, height: height)

    }else {

        if arrList.count-1 == indexPath.row {
            let width = collectionView.frame.width-10
            let height : CGFloat = 100.0
            return CGSize(width: width, height: height)
        }else{
            let width = (collectionView.frame.width-20)/2
            let height : CGFloat = 100.0
            return CGSize(width: width, height: height)
        }
    }

}

This is interspacing methods. 这是间隔方法。

//these methods are to configure the spacing between items

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(0,5,5,5)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 10
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 10
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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