UICollectionView Set number of columns

后端 未结 17 1160
执笔经年
执笔经年 2020-11-28 17:28

I just started learning about UICollectionViews. I\'m wondering if anyone knows how to specify the number of columns in a collectionview. The default is set to 3 (iPhone/por

17条回答
  •  执笔经年
    2020-11-28 18:13

    If you are lazy using delegate.

    extension UICollectionView {
        func setItemsInRow(items: Int) {
            if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout {
                let contentInset = self.contentInset
                let itemsInRow: CGFloat = CGFloat(items);
                let innerSpace = layout.minimumInteritemSpacing * (itemsInRow - 1.0)
                let insetSpace = contentInset.left + contentInset.right + layout.sectionInset.left + layout.sectionInset.right
                let width = floor((CGRectGetWidth(frame) - insetSpace - innerSpace) / itemsInRow);
                layout.itemSize = CGSizeMake(width, width)
            }
        }
    }
    

    PS: Should be called after rotation too

提交回复
热议问题