我有垂直向上滚动的 UICollectionView
,我想在点击时更改项目高度。在默认状态下,单元格的高度为屏幕高度的 2/3。我试过以下:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
if let cell = cell as? TutorialCell {
let attribute = layout.layoutAttributesForItem(at: indexPath)
attribute?.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width,
height: UIScreen.main.bounds.size.height)
collectionView.reloadItems(at: [indexPath])
}
print(indexPath.row)
}
但它不起作用。
最佳答案
您可以通过 UICollectionViewDelegateFlowLayout
方法 sizeForItemAt
实现此目的
声明一个变量
var selectIndex: Int = -1
在你的didSelectItemAt
中添加这个
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectIndex = indexPath.row
collectionView.reloadData()
}
为 UICollectionViewDelegateFlowLayout
添加扩展
extension YourViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = (self.selectIndex == indexPath.row ) ?
UIScreen.main.bounds.size.height :
(UIScreen.main.bounds.size.height * 2) / 3
return CGSize(width:UIScreen.main.bounds.size.width, height:height)
}
}
关于ios - 点击扩展 UICollectionViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55619885/