如何使用swift在collectionview中实现显示/隐藏部分



我在整个互联网上搜索过,我不确定是否能做到,因为我是iOS开发的新手。我希望我的应用程序何时开始只显示标题的第一部分和我的单元格。然后,当我点击我的一个单元格时,我想从第2节下面显示我的标题和单元格等。我已经正确设置了单元格和节,我也可以正确选择每个单元格和更改背景颜色等。我的应用程序运行,但它一次显示所有的节和单元格。

例如:

应用程序启动,我必须只看到第1节:

第1节标题

cell1 cell2cell3

然后我点击单元格1,我必须只看到第1节和第2节:

第1节标题

cell1 cell2cell3

第2节标题

cell1 cell2cell3cell4

然后我点击单元格4,我必须只看到第1节、第2节和第3节:

第1节标题

cell1 cell2cell3

第2节标题

cell1 cell2cell3cell4

第3节标题

cell1 cell2

等等。

我发现我必须使用下面提到的这些方法,但我不知道如何实现我的集合中的显示/隐藏部分。

这是我的代码:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
if indexPath.section == 0 {
if (indexPath.row == 0) {cell!.contentView.layer.backgroundColor =  colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1)}
if (indexPath.row == 1) {cell!.contentView.layer.backgroundColor =  colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1)}
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
if indexPath.section == 0 {
if (indexPath.row == 0) { cell!.contentView.layer.backgroundColor =  colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)}
if (indexPath.row == 1) { cell!.contentView.layer.backgroundColor =  colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)}
}
}
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { 
}

如果您正在对数据进行建模,以便跟踪应该隐藏的部分(以及单元格背景颜色),这将有所帮助。也许你已经是了,但我只举一个例子:

class MyModelSection {
var items = [MyModel]()
var hidden = true
}
class MyModel {
var backgroundColor: UIColor?
}
class MyViewController: UICollectionViewController: {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var dataSource = [MyModelSection]()
var visibleDataSource: [MyModelSection] {
return dataSource.filter { !$0.hidden }
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}

然后您可以使用UICollectionViewDataSource协议来确定应该显示的部分

func numberOfSections(in collectionView: UICollectionView) -> Int {
return visibleDataSource.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return visibleDataSource[section].items.count
}

在你列出的功能中,我想你会使用:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Not sure how your logic for picking which one gets displayed...
guard visibleDataSource.count >= indexPath.section else {
return
}
let dataForNextSection = visibleDataSource[indexPath.section + 1]
dataForNextSection.hidden = false
collectionView.reloadData()
}

最新更新