Search code examples
iosswift5uicollectionviewflowlayout

Why doesn't the UICollectionViewFlowLayout work well?


I would like to use FlowLayout to show two Items in one line by using the following code:

override func viewDidLoad()
    {
        super.viewDidLoad()
        setupCV()
    }

func setupCV()
    {
        collectionView.delegate = self
        collectionView.dataSource = self
        let width = (view.frame.size.width - 10) / 2
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: width, height: width + 80 )
    }

However, when I run the project, it shows me like that: enter image description here

When I debug it, the return value of the width is correct. enter image description here

The Size setting of the collection view is also correct I think: enter image description here

I also try to put the layout setting part in this function:

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

However, Xcode doesn't even excute this function.

Any Idea of what happened and how can I fix this issue? Many thanks!


Solution

  • Set the layout back to collectionView:

    let layout = UICollectionViewFlowLayout()
    layout.itemSize = CGSize(width: width, height: width + 80)
    collectionView.collectionViewLayout = layout