【问题标题】:Gradient for UIButtonUIButton 的渐变
【发布时间】:2017-05-29 13:10:45
【问题描述】:

请我需要一些代码来制作按钮背景渐变颜色,请我不知道如何制作。我已经尝试过使用层和像这段代码这样的公共类,但该类没有出现

public class GradientButton: UIButton {

override public func layoutSubviews() {
    super.layoutSubviews()
    layoutGradientButtonLayer()
}

// MARK: Private
private func layoutGradientButtonLayer() {
    let gradientLayer = CAGradientLayer()
    let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).cgColor as CGColor
    let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).cgColor as CGColor
    gradientLayer.colors = [color1, color2]
    gradientLayer.locations = [0.0, 1.0]
    self.layer.addSublayer(gradientLayer)
}

}

【问题讨论】:

标签: swift button gradient


【解决方案1】:
extension UIView {
    func applyGradient(colours: [UIColor]) -> Void {
        self.applyGradient(colours, locations: nil)
    }

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

class ViewController: UIViewController {

    @IBOutlet weak var btn: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.btn.titleLabel?.textColor = UIColor.whiteColor()

        self.btn.applyGradient([UIColor.yellowColor(), UIColor.blueColor()])
        self.view.applyGradient([UIColor.yellowColor(), UIColor.blueColor(), UIColor.redColor()], locations: [0.0, 0.5, 1.0])
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

【讨论】:

    【解决方案2】:

    我认为你应该在layoutSubViews() 中将gradientLayer.frame 设置为self.bounds,应该没问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多