4

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

Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
iamVishal16
  • 1,780
  • 18
  • 40

1 Answers1

6

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.

Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
  • I have changed a number of cells to 10 and field8, field9 goes to next column and now it's scroll horizontally. But How can I achieve a single cell will go to the next column? – iamVishal16 Aug 27 '18 at 09:02
  • @Vishal16 Try reducing the collection view size or increasing the item size. – Rakesha Shastri Aug 27 '18 at 09:07