How to set UICollectionViewCell Width and Height programmatically

后端 未结 20 1206
终归单人心
终归单人心 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:01

    Use this method to set custom cell height width.

    Make sure to add this protocols

    UICollectionViewDelegate
    
    UICollectionViewDataSource
    
    UICollectionViewDelegateFlowLayout
    

    If you are using swift 5 or xcode 11 and later you need to set Estimate Size to none using storyboard in order to make it work properly. If you will not set that than below code will not work as expected.

    Swift 4 or Later

    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)
        }
    }
    

    Objective-C

    @interface YourViewController : UIViewController
    
    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        return CGSizeMake(CGRectGetWidth(collectionView.frame), (CGRectGetHeight(collectionView.frame)));
    }
    

提交回复
热议问题