【问题标题】:Set UIButton's background as a CAGradientLayer将 UIButton 的背景设置为 CAGradientLayer
【发布时间】:2019-10-13 17:32:58
【问题描述】:

如何将 UIButton 的背景设置为 CAGradientLayer?

我尝试了以下方法:

func applyGradient(colors: [UIColor], locations: [NSNumber]?) -> Void {
    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = colors.map { $0.cgColor }
    gradient.locations = locations
    self.layer.insertSublayer(gradient, at: 0)
}

我从Set Background Gradient on Button in Swift得到的

然后使用它:

let startButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Get Started", for: .normal)
    button.setTitleColor(AppSettings.PURPL_COLOR, for: .normal)
    button.titleLabel?.font = UIFont(name: "Rubik-Medium", size: 16.0)
    return button
}()

startButton.applyGradient(colors: [.red, .blue], locations: nil)

另外,我将按钮的宽度设置为视图的宽度,将高度设置为 50。

但是,当我运行它时,我得到的是:

不应用背景渐变。

【问题讨论】:

    标签: swift xcode


    【解决方案1】:

    当您调用方法applyGradient时,按钮的Bounds将为0。所以创建一个UIButton子类,在layoutSublayers方法中改变渐变层frame

    class GradientButton: UIButton {
        let gradient: CAGradientLayer = CAGradientLayer()
        internal override init(frame: CGRect) {
            super.init(frame: frame)
        }
        internal required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
        required init(_ colors: [UIColor], locations: [NSNumber]?) {
            super.init(frame: .zero)
            applyGradient(colors,locations:locations)
        }
        func applyGradient(_ colors: [UIColor], locations: [NSNumber]?) {
            gradient.colors = colors
            gradient.locations = locations
            gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
            gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
            layer.insertSublayer(gradient, at: 0)
        }
        override func layoutSublayers(of layer: CALayer) {
            super.layoutSublayers(of: layer)
            gradient.frame = self.bounds
        }
    }
    

    并使用颜色和位置值创建按钮

    let button = GradientButton([.red,.blue], locations: nil)
    

    【讨论】:

    • 谢谢你,我宁愿只使用 UIButton。在 viewDidLayoutSubviews 中应用渐变会好吗?
    • @OmarHashim 是的。拨打startButton.applyGradient(colors: [.red, .blue], locations: nil)viewDidLayoutSubviews
    • @OmarSinan 但是viewDidLayoutSubviews 方法在视图控制器中被多次调用。每次调用applyGradient 方法时,它都会添加一个新层。考虑使用UIButton 子类或保留对gradientLayer 的引用
    • 哦,对了,我没想到。感谢您的提醒!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2018-06-29
    相关资源
    最近更新 更多