How to set UICollectionViewCell Width and Height programmatically

后端 未结 20 1203
终归单人心
终归单人心 2020-12-04 08:06

I am trying to implement a CollectionView. When I am using Autolayout, my cells won\'t change the size, but their alignment.

Now I would rather want to

20条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 09:07

    **Swift 5**
    To make this work you have to do the following.
    
    Add these protocols
    
     - UICollectionViewDelegate
    
    
     - UICollectionViewDataSource
    
    
     - UICollectionViewDelegateFlowLayout
    
    Your code will then look like this
    
    extension YourViewController: UICollectionViewDelegate {
        //Write Delegate Code Here
    }
    
    extension YourViewController: UICollectionViewDataSource {
        //Write DataSource Code Here
    }
    
    extension YourViewController: UICollectionViewDelegateFlowLayout {
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: screenWidth, height: screenWidth)
        }
    }
    
    Now the final and crucial step to see this take effect is to go to your viedDidLoad function inside your Viewcontroller.
    
        override func viewDidLoad() {
            super.viewDidLoad()
            collection.dataSource = self // Add this
            collection.delegate = self // Add this
    
            // Do any additional setup after loading the view.
        }
    
    Without telling your view which class the delegate is it won't work.
    

提交回复
热议问题