Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView showing vertically even when scroll direction is set to horizontal?

I am trying to paint UIScrollView list horizontally using this code but not working expected?

    let nib = UINib(nibName: cellIdentifier, bundle: nil)
    collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier)
    collectionView.collectionViewLayout = layout(withParentView: view)

    self.collectionView.delegate = self
    self.collectionView.dataSource = self

Flow Layout method

// #PRAGMA mark - UICollectionViewFlowLayout()

func layout(withParentView parentView: UIView) -> UICollectionViewFlowLayout {
    let layout = UICollectionViewFlowLayout()
    layout.itemSize = CGSize(width: 160, height: 65)
    layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0
    layout.scrollDirection = .horizontal
    return layout
}

and here is the delegate and dataSource methods

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 2
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! RowCollectionViewCell

    if indexPath.row % 2 == 0 {
        cell.backgroundColor = UIColor(red: 248/255, green: 248/255, blue: 248/255, alpha: 1)
    }else {
        cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
    }

    cell.label.text = "Field\(indexPath.row)"

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

}

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

When I run it shows this (Vertical list of items). Is there anything I have missed out. Any help would be appreciated.

enter image description here

like image 396
iamVishal16 Avatar asked Nov 16 '25 05:11

iamVishal16


1 Answers

Flow layout uses a line-based layout. What this means for you is that if you set the scroll direction to horizontal, then the cells will be laid out in a line form top to bottom until no more space is available and then move on to the next line.

You can verify this easily by changing the number of cell to something higher. (like 10?)


I recommend you watch this video to get a better understanding of how UICollectionView works.

like image 175
Rakesha Shastri Avatar answered Nov 17 '25 21:11

Rakesha Shastri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!