简体   繁体   中英

Load a UICollectionViewCell with different alpha value than its UICollectionView

I am having trouble giving my UICollectionViewCell a different alpha than the UICollectionView that owns them. I have looked at a few other posts like this one but none have worked for me. I have a .xib file with the UICollectionView where the alpha is set to 0.9, and the cells inside are loaded from another .xib file with their alpha set to 1.0. The UICollectionView 's alpha takes precedence no matter what I have tried. These attempts include:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! Cell

// Here is the first attempt
    cell.alpha = 1.0
    cell.contentView.alpha = 1.0

// Here is the second attempt
    let attribute = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
    attribute.alpha = 1.0
    cell.applyLayoutAttributes(attribute)

    cell.setNeedsDisplay()
    return cell

I want the cells to load with no transparency, but I want the collection view housing them to be slightly transparent. There is a unique image loaded on each cell that cannot be transparent at all.

Edit1: I tried setting the backgroundColor of the UICollectionView to clear with a 1.0 alpha, then giving it a custom backgroundView in my viewDidLoad() method. I have an @IBOutlet of the collection view that I use to set the following:

@IBOutlet weak var collectionView: UICollectionView!

// MARK: -View Lifecycle
override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.delegate = self
    collectionView.dataSource = self

    let background = UIView(frame: collectionView.bounds)
    background.backgroundColor = UIColor(red: 26/255.0, green: 26/255.0, blue: 26/255.0, alpha: 0.97)
    collectionView.backgroundView = background

    collectionView.registerNib(UINib(nibName: "Cell", bundle: nil), forCellWithReuseIdentifier: "Cell")

}

This DID work.

You can´t have parent view with alpha != 1 and its childs with alpa=1, they wont work as expected.

Usually what i do is use an aux view (same frame as the collection View), sibling of the parent (your collection view) view with the alpha set to X value. Set the collection view background's color to clearColor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM