在自定义UIButton子类上添加带有圆角的阴影层

时间:2018-10-12 19:41:45

标签: ios swift uibutton

我正在尝试在自定义UIButton子类上应用阴影和圆角,以在情节提要中使用

这是我的代码:

import UIKit

class customButton: UIButton {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
    setGradientBackground()
    setShadowLayer()
}

private func setup() {
    clipsToBounds = true
    layer.cornerRadius = 8
}

private func setGradientBackground() {

    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = bounds
    gradientLayer.colors = [
        UIColor(red: 0.18, green: 0.5, blue: 0.93, alpha: 1).cgColor,
        UIColor(red: 0.18, green: 0.61, blue: 0.86, alpha: 1).cgColor
    ]
    gradientLayer.locations = [0,1]
    gradientLayer.startPoint = CGPoint(x: 0.25, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 0.75, y: 0.5)

    layer.insertSublayer(gradientLayer, at: 0)
}

private func setShadowLayer(){

    let subLayer = CALayer()
    subLayer.frame = bounds
    subLayer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 8).cgPath
    subLayer.shadowColor = UIColor.red.cgColor
    subLayer.shadowOpacity = 1
    subLayer.shadowRadius = 12
    subLayer.shadowOffset = CGSize(width: 0, height: 2)

    layer.insertSublayer(subLayer, at: 0)
}

}

当我将clipsToBounds设置为true时,它会消除阴影,因此我决定添加一个新的子层func setShadowLayer(),到目前为止没有任何效果。

1 个答案:

答案 0 :(得分:1)

还尝试在渐变图层上设置.cornerRadius

    gradientLayer.endPoint = CGPoint(x: 0.75, y: 0.5)

    // add this line        
    gradientLayer.cornerRadius = 8

    layer.insertSublayer(gradientLayer, at: 0)

我的结果:

enter image description here