Vladimir Zhelnov
Vladimir Zhelnov

Reputation: 3

Resizing CollectionViewCell in UIView

I have CollectionView in UIView. How to resize CollectionViewCell to 50% of screen width? I want to create 2 columns in CollectionView.

class Class_MyUIViewClass: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate 
{

Also i have image and label in CollectionViewCell.

Upvotes: 0

Views: 123

Answers (2)

shallowThought
shallowThought

Reputation: 19602

Assuming you know the desired cell height, conform to UICollectionViewDelegateFlowLayout:

class Class_MyUIViewClass: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

and implement sizeForItemAtIndexPath:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let desirednumberOfCollumns: CGFloat = 2
    let width = collectionView.frame.width / desirednumberOfCollumns
    return CGSize(width, yourHeight)
}

Upvotes: 0

Rajat
Rajat

Reputation: 11127

You can use sizeForItemAt method of UICollectionView to manage cell size of it

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let screenWidth = UIScreen.main.fixedCoordinateSpace.bounds.width
    return CGSize(width: screenWidth/2, height: yourHeight)
} 

Also confirms to UICollectionViewDelegateFlowLayout

Upvotes: 1

Related Questions