[英]Swift UICollectionView Show/Hide Items on Tap
在 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 Simulator 屏幕截图,转换为 GIF)。 请注意,当隐藏/降低较高项目的高度时,蓝色框会在较低项目后面进行动画处理。
有没有更好的方法来实现这一点?
您可以通过将 UILabel 添加为 collectionview Section 并将 expandad/collapsed view 添加为 row 来实现这一点。 当用户选择标签时,您可以更改行高
声明部分编号:
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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.