I am writing an iOS card game. I am displaying the player's cards in a collection view with horizontal scrolling.
When a card is selected, I want that card to "pop up" a bit. This means that it should move up by 10% of its height.
This is how I approached the problem:
I overrode this method to calculate the size of each cell:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// the height of each card should be a bit smaller than the collection view
// height so there is some space for the card to pop up
let height = collectionView.height / 1.15
// 5:7 is the W:H ratio of each card
let width = height * 5 / 7
return CGSize(width: width, height: height)
}
In each cell, there is an imageView
that completely fills the cell. I did this with constraints. Here is the cell class:
class CardCell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
override var isSelected: Bool {
didSet {
if isSelected {
self.transform = .identity
} else {
// when it is not selected, it is transformed downwards because
// identity transformation will place the cell at the top of the
// collection view
self.transform = CGAffineTransform(translationX: 0, y: self.bounds.height * 0.1)
}
}
}
}
In cellForItemAt
, I did the following:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CardCell
cell.isSelected = false
cell.imageView.image = ...
return cell
}
This is all well and good and appears to work.
When the device orientation changes, the collection view will change its size accordingly (I have added constraints on the collection view as well). This means that I need to recalculate the size for the cells again, so I call collectionView.reloadData()
in viewWillTransitionTo
. This is where it doesn't work. After an orientation change, some of the cells doesn't seem to be transformed downwards. If I tap on these cells, they will be transformed further upwards, exceeding the collection view's bounds.
I checked the debugger and found that these abnormal cells indeed have the identity transformation in the selected state. That shouldn't happen, right? The collection view should by default position all its cells inside its bounds, right?
How can I make it so that all the cells are transformed downwards even after an orientation change?