如果我在cellForItemAtIndexPath中设置一个单元格的alpha属性,如下所示……
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 }
…最初出现的细胞是不透明的(α为1.0).如果我滚动,出现的“新”(重用)单元格具有预期的alpha值.如果我滚动回到开头,“原始”单元格(开始不透明)现在也具有预期的alpha值.
为什么在初始加载时未设置alpha值?
其他不起作用的尝试:
>将此添加到委托,我得到相同的结果:
func collectionView(collectionView: UICollectionView,willDisplayCell cell: UICollectionViewCell,forItemAtIndexPath indexPath: NSIndexPath) { cell.alpha = 0.5 }
>将其添加到cellForItemAtIndexPath:
let attrs = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) attrs.alpha = 0.5 cell.applyLayoutAttributes(attrs)
解决方法
我相信这种情况正在发生,因为Apple正在对单元格进行一些特殊的内部处理,作为UICollectionView的一部分.如果在单元格的contentView属性上设置alpha,则alpha会按预期保持不变.
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.
如果您有backgroundView或selectedBackgroundView,则需要单独设置其alpha.