更改选定的UICollectionView单元格的大小

5

我有一个简单的UICollectionViewController,其中返回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)
    }
}
1个回答

18

您可以检查sizeForItemAt中的indexPath是否被选中。如果是,则返回不同的高度,否则返回标准高度。

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)
    }
}

请您能否提供一个例子?谢谢。 - Daniel Dramond
如何修改代码,使得当我再次点击同一个单元格时,它可以返回到之前的大小? - Luke Irvin
点击同一个单元格将取消选择 - 您可以使用委托方法 didDeselectItemAt 来识别此操作,并类似地调用 performBatchUpdates 以便在 switch 语句中将单元格恢复为默认大小。 - Callam
由于某种原因,这不会使更改动画化。它确实改变了高度,但它没有使更改动画化,它只是直接从一个高度到另一个高度。有什么想法吗?我正在使用完全相同的代码。 - tapizquent
我以前从未见过像这样开启“Optional”的方式,我很喜欢它。 - Luke Rogers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接