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

标签 ios swift uibutton

我正在尝试在自定义 UIButton 子类上应用阴影和圆角以在 Storyboard上使用

这是我的代码:

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()到目前为止没有任何效果。

最佳答案

尝试在渐变层上设置 .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

关于ios - 在自定义 UIButton 子类上添加带圆角的阴影层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52786058/

相关文章:

ios - 如何根据 numberOfItemsInSection 的数量设置 heightForRowAt?

iOS UIButton、setEnabled 和 button.hidden 不工作

ios - 删除 iOS 应用本地化

ios - 在安装 iOS 应用程序时提醒用户所需的 iOS 版本

ios - Swift 4.2 - Cocoapods : Adding and accessing scnassets in resource_bundles

ios - UIButtons 在动画期间没有响应 - iOS Swift 3

ios - 如何使用 Alamofire 发布复合关键数据参数?

swift - 将函数重新格式化为 swift 3.0 语法

iphone - 如何在按钮中存储字符串值(不能使用标签。)

ios - 单击按钮时如何更改按钮的文本? - swift