简体   繁体   中英

Swift - Change UICollectionViewCell size programmatically

I am struggling to change the size my items in the CollectionView.

Custom Flowlayout class found here :

This is my CollectionView:

class ExampleViewController: UIViewController, UICollectionViewDataSource {

let theCollectionView: UICollectionView = {
    let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
    v.translatesAutoresizingMaskIntoConstraints = false
    v.backgroundColor = .white
    v.contentInsetAdjustmentBehavior = .always
    v.layer.cornerRadius = 30
    return v
}()

let columnLayout = FlowLayout(
    itemSize: CGSize(width: 50, height: 50),
    minimumInteritemSpacing: 10,
    minimumLineSpacing: 10,
    sectionInset: UIEdgeInsets(top: 20, left: 20, bottom: 10, right: 20)
)

I tried changing the itemSize but that doesnt do anything.

columnLayout is not used, you need to replace UICollectionViewFlowLayout() with it.

let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: columnLayout)

Here is Code for CollectionViewCell Size Change

(Note:- Change values according to your Requirement!)

 let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
        layout.itemSize = CGSize(width: screenWidth/4, height: screenWidth/4)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        cell2.collectionView2.collectionViewLayout = layout

You didn't assigned you flowLayout to the collectionView either try:

theCollectionView.collectionViewLayout = columnLayout or

First define your layout:

let columnLayout = FlowLayout(...

Then define your collectionView like this:

let theCollectionView: UICollectionView = { let v = UICollectionView(frame: CGRect.zero, collectionViewLayout:columnLayout)

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