Alexandre Odet
Alexandre Odet

Reputation: 75

UICollectionView Horizontal Scroll

I try to do a UICollectionView that print 1,5 cell on screen, and with the scroll you should be able to display the next cells. But here is the problem, I manage to display 1,5 cell but I can't scroll. I don't know why, when I set the layout scrollDirection property to .Horizontal, that creates a Vertical scroll.

Here is the layout and UICollectionView initialization:

let screenSize = UIScreen.mainScreen().bounds
let widthImage = (screenSize.width - CGFloat(8)) / 1.5
let heightImage = UIUtils.getHeightAspectRatio(widthImage)
//let sizeCollectionView: CGSize = CGSize(width: widthImage, height: heightImage)

let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: widthImage, height: heightImage)

howTo = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
howTo!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "howToCell")
howTo!.tag = 0
howTo!.delegate = self
howTo!.dataSource = self
self.view.addSubview(howTo!)
howTo!.snp_makeConstraints { (make) -> Void in
  make.top.equalTo(readMoreText.snp_bottom).offset(5)
  make.leading.equalTo(self.view).offset(5)
  make.trailing.equalTo(self.view)
  make.height.equalTo(115)
}
howTo?.backgroundColor = UIColor.whiteColor()
howTo?.contentMode = .ScaleToFill
howTo?.scrollEnabled = true

And here is the method called when you display the cell:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if collectionView.tag == howTo!.tag {
  let cell = collectionView.dequeueReusableCellWithReuseIdentifier("howToCell", forIndexPath: indexPath)
  if let url = NSURL(string:UIUtils.getImageUrl(self.exercise.getHowTos()[indexPath.row].getImages(), label: Image.mediumWide)) {
    let screenSize = UIScreen.mainScreen().bounds
    let widthImage = (screenSize.width - CGFloat(8)) / 1.5
    let heightImage = UIUtils.getHeightAspectRatio(widthImage)
    let img = UIImageView(frame: CGRect(x: 0, y: 0, width: widthImage, height: heightImage))
    img.af_setImageWithURL(url)
    cell.contentView.addSubview(img)
    cell.backgroundView = cell.contentView
  } else {
    let img = UIImageView(frame: cell.frame)
    img.image = R.image.appIconTemp()
    cell.contentView.addSubview(img)
    cell.backgroundView = cell.contentView
    //cell.backgroundColor = UIColor.blackColor()
  }

If you have any idea why I can't scroll you'll made my day !

Thanks

Upvotes: 2

Views: 11178

Answers (1)

Prashant Ghimire
Prashant Ghimire

Reputation: 548

try this

 let layout = UICollectionViewFlowLayout()

 layout.scrollDirection = .Vertical

 let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)

just change the scroll direction according to your need

Upvotes: 8

Related Questions