How to set UICollectionViewCell Width and Height programmatically

后端 未结 20 1270
终归单人心
终归单人心 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 08:49

    #Absolutely simple way:

    class YourCollection: UIViewController,
         UICollectionViewDelegate,
         UICollectionViewDataSource {
    

    #You must add "UICollectionViewDelegateFlowLayout" or, there is no autocomplete:

    class YourCollection: UIViewController,
         UICollectionViewDelegate,
         UICollectionViewDataSource,
         UICollectionViewDelegateFlowLayout {
    

    #Type "sizeForItemAt...". You're done!

    class YourCollection: UIViewController,
         UICollectionViewDelegate,
         UICollectionViewDataSource,
         UICollectionViewDelegateFlowLayout {
     
         func collectionView(_ collectionView: UICollectionView,
          layout collectionViewLayout: UICollectionViewLayout,
          sizeForItemAt indexPath: IndexPath) -> CGSize {
         
         return CGSize(width: 37, height: 63)
    }
    

    That's it.

    Example, if you want "each cell fills the whole collection view":

         guard let b = view.superview?.bounds else { .. }
         return CGSize(width: b.width, height: b.height)
    

提交回复
热议问题