【问题标题】:Collection view tiling集合视图平铺
【发布时间】:2016-05-10 16:38:07
【问题描述】:

我正在尝试使用包含 2 列图像的滚动集合视图。最终图像的高度不同,但宽度相同,垂直仅占屏幕的一半,但正如您所见,黑色空间很大。

这里是代码。

import UIKit

类 ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

let screenSize: CGRect = UIScreen.mainScreen().bounds
@IBOutlet var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        let itemWidth = CGFloat(Int(view.bounds.width / 3.0))
        let itemHeight = layout.itemSize.height
        layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        layout.invalidateLayout()
    }


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as UICollectionViewCell!
    return cell
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    collectionView.registerClass(ImageCell.self, forCellWithReuseIdentifier: "Cell")
    return 10
}

}

对于细胞本身:

import Foundation
import UIKit

class ImageCell: UICollectionViewCell{

var imageView: UIImageView!


override init(frame: CGRect) {
    super.init(frame: frame)

}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
    imageView.contentMode = UIViewContentMode.ScaleAspectFit
    imageView.image = UIImage(named: "defaultImage.jpg")
    contentView.addSubview(imageView)

    //fatalError("init(coder:) has not been implemented")
}
}

【问题讨论】:

  • 您需要查看UICollectionViewFlowLayout 的minimumLineSpacing 和minimumInteritemSpacing 属性。您可以在流程布局上调整这些属性以摆脱空间。请参阅文档here。您还需要确保您的项目宽度能够利用屏幕上的可用空间。

标签: ios uicollectionview


【解决方案1】:

使用这个委托函数

    func collectionView(_ collectionView: UICollectionView,
                          layout collectionViewLayout: UICollectionViewLayout,
          sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

            CGSize screenSize=UIScreen.mainScreen().bounds.size

        return CGSizeMake(screenSize.width/2, yourheighteOfImage);
        }

    func collectionView(_ collectionView: UICollectionView,
                                      layoutcollectionViewLayout:UICollectionViewLayout,minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
       return 0.0
    }

【讨论】:

  • 这里也只返回图片的高度
猜你喜欢
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
  • 2018-04-29
  • 1970-01-01
相关资源
最近更新 更多