ios - Swift UICollectionView 在点击时显示/隐藏项目
问题描述
在 UICollectionView 中,我想在点击项目时显示/隐藏更多内容。
目前,我正在通过在 Storyboard 上设计一个更大的单元格来做到这一点,我只想在顶部显示 UILabel。当一个项目被点击时,didSelectItemAt()
和sizeForItemAt()
调用被编码为:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndex = indexPath.item
print("didSelectItemAt: \(selectedIndex)")
collectionView.reloadItems(at: [indexPath])
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var size = CGSize()
size.width = collectionView.frame.width
size.height = 50
if let index = selectedIndex {
print("SizeForItemAt item:\(indexPath.item), \(index)")
if index == indexPath.item {
size.height = 150
} else {
size.height = 50
}
}
return size
}
其中有这个输出(取自 iPhone 模拟器屏幕截图,转换为 GIF)。请注意,当隐藏/减小较高项目的高度时,蓝色框会在较低项目后面进行动画处理。
有没有更好的方法来实现这一点?
解决方案
您可以通过将 UILabel 添加为 collectionview 部分并将展开/折叠视图添加为行来实现此目的。当用户选择标签时,您可以更改行高
声明节号:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
在节中声明行数:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if indexPath.section == 0{
return 1
}
else indexPath.section == 1{
return 1
}
return 0
}
然后填写您的部分和行cellForRowAt
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! CellViewController
if indexPath.section == 0{
cell.yourLabel.text = "bla bla"
if indexPath.row == 0{
// You can declare another cell in here
let blueViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "blueViewCellID", for: indexPath) as! BlueViewController
}
}
}
并且在sizeForItemAt
功能上
func collectionView(_ collectionView : UICollectionView,layout collectionViewLayout : UICollectionViewLayout,sizeForItemAt indexPath : IndexPath) -> CGSize{
if indexPath.section == 0{
if indexPath.row == 0{
if firstSectionOpened == true {
return 50
}else{ return 0 }
}
let width = collectionView.frame.width / CGFloat(4)
return CGSize(width: width, height: width)
}
}
然后在 didSelect
var firstSectionOpened : Bool = false
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.section == 0 {
if firstSectionOpened == true{
firstSectionOpened = false
}
else{
firstSectionOpened = true
}
self.myCollection.reloadData()
}
}
推荐阅读
- jquery - 为什么jQuery触发函数从数组中删除数据?
- flutter - 在此 ContactsPage 小部件上方找不到正确的 Provider<...>
- redis - 使用 Redis RDB 的 Hangfire 作业创建吞吐量性能
- javascript - 我可以获取鼠标事件单击的字符串的索引吗?
- python - 安装熊猫失败
- vector - 将 Mbtiles 提取到 PBF 以使用 OpenLayers 自己托管它
- php - 我尝试使用工厂类播种,但得到 BadMethodCallException : Call to undefined method Database\Factories\ProductFactory::unique()
- android - 选择音频文件并点击按钮播放
- graphql - Apollo 未能在 fetchMore 调用上合并缓存
- android-studio - android studio:将recycleview放在具有透明背景的Edittext之上