从UIView删除特定的子层

时间:2019-06-17 05:12:21

标签: swift user-interface uikit swift5

我正在尝试从UIButton视图中删除特定的子层

我尝试了self.view.layer.sublayer.removeall(),但它使应用程序崩溃

func setViewState(viewState: StartButton.ViewState) {

    switch (viewState) {

    case .disabled:
        self.backgroundColor = UIColor.clear
        self.layer.borderColor = StartButton.disabledButtonColor?.cgColor
        self.setTitleColor(StartButton.disabledButtonColor, for: .normal)

        self.isEnabled = false

    case .enabled:
        self.layer.borderWidth = 0
        self.setTitleColor(.black, for: .normal)
        let buttonGradient = CAGradientLayer()
        buttonGradient.frame = CGRect(x: 0, y: 0, width: 311, height: 80)
        buttonGradient.colors = [
            UIColor.white.cgColor,
            UIColor(red:0.94, green:0.94, blue:0.96, alpha:1).cgColor
        ]

        buttonGradient.locations = [0, 1]
        buttonGradient.startPoint = CGPoint(x: 0.5, y: 0)
        buttonGradient.endPoint = CGPoint(x: 0.5, y: 1)
        self.layer.insertSublayer(buttonGradient, at: 0)

        self.layer.shadowOffset = CGSize(width: 0, height: 12)
        self.layer.shadowColor = UIColor(red:0, green:0, blue:0, alpha:0.15).cgColor
        self.layer.shadowOpacity = 1
        self.layer.shadowRadius = 34

        self.layer.masksToBounds = true
        self.isEnabled = true
    }
}

我希望在启用禁用案例的情况下删除渐变层

1 个答案:

答案 0 :(得分:1)

您可以在创建时设置渐变层的name,并使用它从filter层开始removeparent,如下所示,

let buttonGradient = CAGradientLayer()
buttonGradient.name = "Gradient"

// Removing
self.layer.sublayers?.first(where: { $0.name == "Gradient"})?.removeFromSuperlayer()