【发布时间】:2018-11-13 05:28:55
【问题描述】:
我有 Single UICollectionView ,我想动态应用两种不同的布局。
-
UICollectionViewFlowLayout: 具有相同大小的单元格和圆形图像的布局。var flowLayout: UICollectionViewFlowLayout { let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: UIScreen.main.bounds.width/3, height: 140) flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) flowLayout.scrollDirection = UICollectionViewScrollDirection.vertical flowLayout.minimumInteritemSpacing = 0.0 return flowLayout } Pintrest Layout: https://www.raywenderlich.com/392-uicollectionview-custom-layout-tutorial-pinterest
例如:当用户单击配置文件按钮时,FlowLayout 将被应用,并且单元格以圆形图像出现。当用户单击图片按钮时,将应用 pintrest 布局,并且单元格将显示为具有动态高度的矩形形状的图像。
最初 CollectionView 有 1.flowLayout,它看起来很完美。但是当我点击图片按钮时,Pintrest 布局与之前的布局混淆,如上图所示。
以下是更改布局的代码。
if isGrid {
let horizontal = flowLayout
recentCollectionView.setCollectionViewLayout(horizontal, animated: true)
recentCollectionView.reloadData()
}
else {
let horizontal = PinterestLayout()
horizontal.delegate = self
recentCollectionView.setCollectionViewLayout(horizontal, animated: true)
recentCollectionView.reloadData()
}
ViewHiarchy:
我有包含标题的主集合视图和一个底部单元格。单元格包含我正在应用多个布局的其他集合视图。我有每个布局的两个不同单元格。我希望底部单元格大小等于content Collection-view 内容大小,以便用户可以垂直滚动整个主 collection-view。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell : UICollectionViewCell!
switch isGrid {
case true:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchProfileCell", for: indexPath)
if let annotateCell = cell as? SearchProfileCell {
annotateCell.photo = photos[indexPath.item]
}
case false:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AnnotatedPhotoCell", for: indexPath)
if let annotateCell = cell as? AnnotatedPhotoCell {
annotateCell.cellwidth = collectionView.contentSize.width/3
annotateCell.photo = photos[indexPath.item]
}
}
cell.contentView.layer.cornerRadius = 0
return cell
}
个人资料和图片按钮操作的代码。
@IBAction func pictureClick(sender:UIButton) {
isGrid = false
self.searchCollectionView.reloadData()
}
@IBAction func profilClick(sender:UIButton) {
isGrid = true
self.searchCollectionView.reloadData()
}
【问题讨论】:
-
尝试 performBatchUpdates
-
你的意思是我应该使用 PerformBatchUpdate 而不是 reloadData 吗?
-
在 performBatchUpdate 块里面放你的布局重置代码
-
好的。让我试试
-
我认为你应该使用 layoutSubviews 而不是 reloadData() 所以在你的 IF 语句之后尝试 self.view.layoutSubviews。你想触发视图控制器的重绘
标签: ios swift uicollectionview uicollectionviewlayout