Home > Mobile >  How to set collection view alpha = 0.5 but header alpha = 1.0
How to set collection view alpha = 0.5 but header alpha = 1.0

Time:06-15

Is it possible to set collection view (all items) alpha = 0.5 but header set alpha = 1.0?

CodePudding user response:

here you can set items alpha:

override func collectionView(_ collectionView: UICollectionView,
                                 cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCell",
                                                      for: indexPath
        cell.alpha = 0.5
 }

here you can set header alpha:

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        switch kind {
            
        case UICollectionView.elementKindSectionHeader:
            
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath)
            
            headerView.backgroundColor = UIColor.blue
            headerView.alpha = 1.0 //by default its also 1 just showing here
            return headerView
            
        case UICollectionView.elementKindSectionFooter:
            break
        default:
            assert(false, "Unexpected element kind")
        }
    }

CodePudding user response:

If your collection have some interitem or interline spacing and collection view have a background color other than clear or systemBackgroundColor, Then you need to set alpha for background color like this :

yourCollectionView.backgroundColor = UIColor.green.withAlphaComponent(0.5)

you can also use backgroundView of collectionView depending upon the need , like this :

    let aView = UIView(frame: yourCollectionView.frame)
    aView.backgroundColor = .green
    aView.alpha = 0.1
    yourCollectionView.backgroundView = aView

and then in cellforItemAt:

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellID", for: indexPath)
        cell.contentView.alpha = 0.5
        return cell
    }
  • Related