【发布时间】: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