我正在尝试使用包含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")
}
}
答案 0 :(得分:0)
使用此委托功能
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
}