Set Background Gradient on Button in Swift

前端 未结 10 1243
礼貌的吻别
礼貌的吻别 2020-12-12 21:54

I have no idea how to set the background gradient on a button (without making the background gradient an image). This is so different from Android.

Here\'s a class I

10条回答
  •  臣服心动
    2020-12-12 22:23

    It's this simple:

    import UIKit
    class ActualGradientButton: UIButton {
    
        override func layoutSubviews() {
            super.layoutSubviews()
            gradientLayer.frame = bounds
        }
    
        private lazy var gradientLayer: CAGradientLayer = {
            let l = CAGradientLayer()
            l.frame = self.bounds
            l.colors = [UIColor.systemYellow.cgColor, UIColor.systemPink.cgColor]
            l.startPoint = CGPoint(x: 0, y: 0.5)
            l.endPoint = CGPoint(x: 1, y: 0.5)
            l.cornerRadius = 16
            layer.insertSublayer(l, at: 0)
            return l
        }()
    }
    

提交回复
热议问题