我想用细胞填充我的collectionview。所以我对它们的大小不同,但它们应该彼此相邻。 我目前的情况如下:
我的Collectionview-Class如下所示:
class OverviewViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
setupCollection()
setupView()
}
private func setupCollection() {
self.collectionView!.register(GoalCell.self, forCellWithReuseIdentifier: goalCellIdentifier)
self.collectionView?.dataSource = self
self.collectionView?.delegate = self
self.collectionView?.backgroundColor = .white
}
private func setupView() {
self.navigationItem.title = "Goals"
if #available(iOS 11.0, *) {
self.navigationController?.navigationBar.prefersLargeTitles = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return DataProvider.sharedInstance.getGoals().count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: goalCellIdentifier, for: indexPath) as! GoalCell
cell.goalEntry = DataProvider.sharedInstance.getGoals()[indexPath.row]
cell.setup()
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellHeight = UIScreen.main.bounds.height / 4.0 - 20
let cellWidth = UIScreen.main.bounds.width / 3.0 - 1.0
let cell = DataProvider.sharedInstance.getGoals()[indexPath.row]
switch cell.type! {
case GoalType.daily:
return CGSize(width: cellWidth, height: cellHeight)
case GoalType.yearly:
return CGSize(width: cellWidth * 2, height: cellHeight * 2)
case GoalType.lifely:
return CGSize(width: cellWidth * 3, height: cellHeight * 3)
}
}
我使用以下代码初始化了我的collectionview:
let overviewFlowLayout = UICollectionViewFlowLayout()
overviewFlowLayout.minimumLineSpacing = 0.0
overviewFlowLayout.minimumInteritemSpacing = 0.0
let overviewVC = OverviewNavViewController(rootViewController: OverviewViewController(collectionViewLayout: overviewFlowLayout))
我真的不知道该怎么办......我希望有人可以帮我一点!谢谢!
答案 0 :(得分:2)
您正在使用UICollectionViewFlowLayout,它不会像您想象的那样工作。要获得第二个屏幕截图中显示的那种布局,您必须编写自己的布局类。
答案 1 :(得分:0)
您必须实现自己的custom collectionViewLayout,或者您可能会尝试找到现成的开源解决方案,或许CHTCollectionViewWaterfallLayout可能足够接近您所寻找的内容。
答案 2 :(得分:0)
最终你需要使用flowlayout,你不能在storyboard中使用约束为collectionviewcell,
此函数将使自定义单元格大小具有边界,我使用它来连续呈现2个单元格
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let paddomg:CGFloat = 25
let collectionviewsize = collectionView.frame.size.width - paddomg
return CGSize(width: collectionviewsize/2 ,height: 120)
}
如果我是你,我将使用两个自定义单元格,并根据索引我将在viewlayout中指定大小和位置