我试图创建一个Nx2(n行,2列)集合视图,其中单元格大小动态调整以完全适合屏幕。
所以我的故事板中有以下控制器:
这是集合视图的约束:
这是相应的View Controller代码:
import UIKit
class SREventAttendeesCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var screenSize: CGRect!
var screenWidth: CGFloat!
var screenHeight: CGFloat!
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
screenSize = UIScreen.mainScreen().bounds
screenWidth = screenSize.width
screenHeight = screenSize.height
let collectionViewWidth = (self.collectionView.frame.size.width/2)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: collectionViewWidth, height: screenHeight/3)
collectionView.setCollectionViewLayout(layout, animated: true)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! SRCollectionViewCell
// Configure the cell
let collectionViewWidth = (self.collectionView.frame.size.width/2)
print(collectionViewWidth)
cell.frame.size.width = collectionViewWidth
cell.nameAgeLabel.frame.size.width = collectionViewWidth
//cell.pictureImageView.image = myImage
return cell
}
}
可悲的是,这导致了以下结果:
有没有人知道我在这里失踪了什么?
答案 0 :(得分:1)
当然,首先,在集合视图流布局方面,您的代码存在一些问题。
1)您不需要像Objective C中那样指定UICollectionViewFlowLayout的类型.Swift可以自动匹配。相反,你应该向下转换为所需的类型(我稍后会讨论)
2)我不会创建新的布局对象并分配它。相反,我只会影响当前的布局对象(请参阅下面的示例代码)
3)您没有考虑minimumInterItemSpacing值,这就是您的单元格每行不适合2的原因。
我会对集合视图流布局代码的实现方式进行一些更改。这就是我将如何实现这一目标(我没有编译它,所以可能会有一些小错误):
let screenWidth = collectionView.bounds.size.width;
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.sectionInset = UIEdgeInsetsMake(0,0,0,0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
let avaliableWidth = screenWidth - (layout.sectionInset.left + layout.sectionInset.right + layout.minimumInteritemSpacing)
let itemWidth = avaliableWidth / 2
// You can set the value of 50 to whatever your height is
layout.itemSize = CGMake(itemWidth, 50)
}