代码之家  ›  专栏  ›  技术社区  ›  Sujal

如何在集合视图中正确呈现渐变视图?

  •  0
  • Sujal  · 技术社区  · 7 年前

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
        collectionView.layoutIfNeeded()
    
        let collectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell
    
        let gradient = CAGradientLayer()
    
        gradient.frame = collectionView.bounds
    
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    
        if indexPath.row % 2 == 0 {
            gradient.colors = [UIColor(hex: 0xD74F9B).cgColor, UIColor(hex: 0xF1828A).cgColor]
        } else {
            gradient.colors = [UIColor(hex: 0x5368D3).cgColor, UIColor(hex: 0x4AAAD1).cgColor]
        }
    
        collectionViewCell.cardView.layer.insertSublayer(gradient, at: 0)
    
        return collectionViewCell
    }
    

    加载集合视图时,我将获得以下视图,其中一个集合视图项将被剪裁。 enter image description here

    但是,当我滚动collection视图时,我得到了正确的呈现视图。 enter image description here

    1 回复  |  直到 7 年前
        1
  •  0
  •   Lal Krishna    7 年前

    问题是添加渐变视图时,bgView没有完全布局。所以界限是零。

    解决方案:

     // CollectionViewCell.swift
    private var gradient: CAGradientLayer?
    
    override func awakeFromNib() {
         super.awakeFromNib()
    }
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            shadowView.layer.shadowPath = UIBezierPath(rect: shadowView.bounds).cgPath
    
            if let gradient = gradient {
                gradient.frame = bgView.bounds
            } else {
                gradient = CollectionViewCell.createGradientLayer(for: bgView)
                bgView.layer.addSublayer(gradient!)
            }
        }
    
    推荐文章