将按钮渐变添加到viewDidLayoutSubviews后不起作用

时间:2019-05-25 11:27:50

标签: ios swift cagradientlayer

我正在使用以下代码添加按钮渐变

extension UIView {
    func applyGradient(colors: [UIColor]) {
        self.applyGradient(colors: colors, locations: nil)
    }

    func applyGradient(colors: [UIColor], locations: [NSNumber]?) {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colors.map { $0.cgColor }
        gradient.locations = locations
        gradient.startPoint = CGPoint(x: 0, y: 0)
        gradient.endPoint = CGPoint(x: 1, y: 0)
        self.layer.insertSublayer(gradient, at: 0)
    }
}

initStyle()中呼叫viewDidLayoutSubviews()无效。

func initStyle() {
    submitBtn.applyGradient(colors: [#colorLiteral(red: 0.1176470588, green: 0.3882352941, blue: 0.5254901961, alpha: 1), #colorLiteral(red: 0.2941176471, green: 0.9098039216, blue: 0.9529411765, alpha: 1)])
    submitBtn.layer.cornerRadius = 15.0
    submitBtn.layer.masksToBounds = true
}

我正在以编程方式创建所有UI元素。我的约束设置正确并且可以正常工作。

lazy var submitBtn: UIButton = {
    let btn = UIButton(type: .system)
    btn.translatesAutoresizingMaskIntoConstraints = false
    btn.setTitle("SUBMIT", for: .normal)
    return btn
}()

如何使其正常工作?


仅当我将initStyle()放置在viewDidAppear()而不是viewDidLayoutSubviews()中时才显示渐变,这会延迟显示按钮渐变。我想避免这种延迟。因此,我将其添加到viewDidLayoutSubviews中,但是渐变没有出现。

3 个答案:

答案 0 :(得分:1)

我认为这里的问题是,在您调用渐变函数时,self.bounds为0。稍后尝试调用它,例如viewWillAppear或调用view.layoutSubViews来触发iewDidLayoutSubviews()

答案 1 :(得分:0)

lazy var submitBtn: UIButton = {
    let btn = UIButton(type: .custom) //Set custom instead of system
    btn.translatesAutoresizingMaskIntoConstraints = false
    btn.setTitle("SUBMIT", for: .normal)
    return btn
}()

答案 2 :(得分:0)

尝试使用内部函数     viewWillAppeare()

为什么不从一开始就在没有单独功能的情况下将渐变应用于按钮?将会使该按钮在已内置渐变的情况下显示。

如果要设置渐变条件,则可以使用以下

func displayButton(condition: Bool){


lazy var submitBtn: UIButton = {
let btn = UIButton(type: .system)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("SUBMIT", for: .normal)

if condition == true {
//set the gradient here
return btn
} else if condition == false
return btn
}

}()



override func viewDidLoad(){
super.viewDidLoad()
 //here you can set the condition to show the gradient or not depending on what you want
displayButton(true) //will show the gradient
displayButton(false) // will show without gradient

}

我目前无法测试此代码,所以我不确定,请尝试一下。