Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the collection view cell size exactly equal to the collection view in iOS?

I want to set a collection view where it is only displayed one element at the time and it scrolls horizontally. I want to know how to set the same size for both if the collection view has equal width with the superview (phone size).

Any help will be really appreciated.

like image 431
Miguelme Avatar asked Nov 04 '16 00:11

Miguelme


People also ask

How do I resize a collection view cell?

First you have to Add the UICollectionViewDelegateFlowLayout delegate and then use following delegate method it will work fine for me. Show activity on this post. Implement the below method,, it is autoresized base on the screen you have.


2 Answers

Simple answer :

Add UICollectionViewDelegateFlowLayout to your class and then use this method:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: yourCollectionView.bounds.width, height: yourCollectionView.bounds.height)
}

to make it horizontal:

enter image description here

like image 185
Dory Daniel Avatar answered Oct 08 '22 12:10

Dory Daniel


if you want to add it programmatically you can try this:

lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.delegate = self
        cv.dataSource = self
        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        return cv
}()
like image 33
Vinicius Vieira Avatar answered Oct 08 '22 12:10

Vinicius Vieira