如何在 swift 中检查和设置 grediant 视图?

How to check and set grediant view in swift?

我想在单击按钮时将渐变颜色设置为背景,以下是我的代码,我在 上崩溃,因为在 sender.subviews 中让 objGrediantView as CAGradientLayer()

查看是否有Grediant

func setGrediantView(sender: AnyObject, topColor: UIColor, bottomColor: UIColor){

    for case let objGrediantView as CAGradientLayer() in sender.subviews {
        if objGrediantView {
            // show error
            return
        }
    }


    let colorTop =  topColor.cgColor
    let colorBottom = bottomColor.cgColor

    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [ colorTop, colorBottom]
    gradientLayer.locations = [ 0.0, 1.0]
    gradientLayer.frame = sender.bounds

    sender.layer.insertSublayer(gradientLayer, at: 0)

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.item)!")
    let dicData = items[indexPath.item]
  //  self.objProfileView.backgroundColor = UIColor.white
     self.setGrediantView(sender: objProfileView, topColor: (dicData["top"]!), bottomColor: (dicData["bottom"]!))
}

将文本改写成这样(你的代码无法编译,我真的很想知道你是怎么做到的):

    for sublayer in (sender.layer.sublayers ?? []) {
        if sublayer is CAGradientLayer  {
            // show error
            return
        }
    }