UICollectionView水平滚动

时间:2016-05-20 09:22:18

标签: ios swift uicollectionview horizontal-scrolling

我尝试在屏幕上打印1,5个单元格UICollectionView,使用滚动条,您应该可以显示下一个单元格。 但问题是,我设法显示1,5个单元格,但我无法滚动。 我不知道为什么,当我将布局scrollDirection属性设置为.Horizontal时,会创建一个垂直滚动。

这是布局和UICollectionView初始化:

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

这是显示单元格时调用的方法:

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()
  }

如果你知道为什么我不能滚动你,那就是我的一天!

由于

1 个答案:

答案 0 :(得分:8)

试试这个

 let layout = UICollectionViewFlowLayout()

 layout.scrollDirection = .Vertical

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

根据需要改变滚动方向