更改所选 UICollectionView 单元格的大小

Changing size of selected UICollectionView Cell

我有一个简单的 UICollectionViewController,它有 returns X 个单元格。我想拥有它,以便选择一个单元格时,特定的选定单元将改变其大小并变大,因为所有其他单元格保持不变。我如何实现这一目标?这是我的代码:

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor(white: 0.90, alpha: 1.0)

        collectionView?.register(PostCell.self, forCellWithReuseIdentifier: cellId)
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.alwaysBounceVertical = true
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let height = (view.frame.width) * 9 / 16
        return CGSize(width: view.frame.width, height: height + 50 + 50)
    }
}

您可以检查是否选择了 sizeForItemAt 中的 indexPath。如果是,您 return 不同的身高,否则 return 标准身高。

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    collectionView.performBatchUpdates(nil, completion: nil)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    switch collectionView.indexPathsForSelectedItems?.first {
    case .some(indexPath):
        return CGSize() // your selected height
    default:
        let height = (view.frame.width) * 9 / 16
        return CGSize(width: view.frame.width, height: height + 50 + 50)
    }
}