ios - 点击扩展 UICollectionViewCell

标签 ios swift uicollectionview

我有垂直向上滚动的 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/

相关文章:

ios - 图像继续快速重新加载到 Collection View 单元格中

swift 4 - 无法在 UIWebView 中显示 pdf

ios - 如何限制 AVAssetWriter 在编码视频时使用过多内存?

swift - CollectionView 中的异步 GET 图像

ios - 无法从collectionView中删除项目

ios - 基于 UIPanGestureRecognizer velocity 的 UIView 动画

ios - 在 iOS 8 中不显示第一个 View Controller 而转到另一个 View Controller

iphone - 请解释这可能是如何泄漏的 - 字符串编码函数

ios - 快速更新聊天客户端 signalR

ios - 如何将在 Collection View 中选择的所有单元格列出到另一个 View 中