If I set a cell's alpha property in cellForItemAtIndexPath
as follows...
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CGPathCell", forIndexPath: indexPath) as UICollectionViewCell
// Prepare cell
cell.alpha = 0.5
cell.setNeedsDisplay()
return cell
}
...the cells that initially appear are opaque (alpha of 1.0). If I scroll, the "new" (reused) cells that appear have the expected alpha value. If I scroll back to the beginning, the "original" cells (which began opaque) now also have the expected alpha value.
Why is the alpha value not set when it is initially loaded?
Additional attempts that don't work:
Adding this to the delegate, I get the same result:
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
cell.alpha = 0.5
}
Adding this to cellForItemAtIndexPath
:
let attrs = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attrs.alpha = 0.5
cell.applyLayoutAttributes(attrs)
I believe this is happening because Apple is doing some special internal handling with the cell as part of a UICollectionView
. If you set the alpha on the cell's contentView
property, the alpha persists as expected.
The UICollectionViewCell docs kind of hint at this:
To configure the appearance of your cell, add the views needed to present the data item’s content as subviews to the view in the contentView property. Do not directly add subviews to the cell itself.
If you have a backgroundView
or selectedBackgroundView
, you'll need to set their alphas separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With