Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionViewCell's alpha property doesn't take effect until reloaded?

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:

  1. Adding this to the delegate, I get the same result:

    func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        cell.alpha = 0.5
    }
    
  2. Adding this to cellForItemAtIndexPath:

    let attrs = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
    attrs.alpha = 0.5
    cell.applyLayoutAttributes(attrs)
    
like image 427
sudo make install Avatar asked Mar 12 '15 17:03

sudo make install


1 Answers

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.

like image 66
bobics Avatar answered Oct 12 '22 15:10

bobics