【问题标题】:Add a resizing UIButton's background with gradient color使用渐变颜色添加调整大小的 UIButton 的背景
【发布时间】:2017-09-06 22:18:42
【问题描述】:

使用此代码,我可以将背景添加到带有渐变的 UIButton:

public func addBackgroundAndGradient(to: UIView, gradient1: CGColor, gradient2: CGColor, cornerRadius: CGFloat = 5){
    let backgroundImage = UIImageView()
    backgroundImage.frame.size = to.frame.size
    backgroundImage.clipsToBounds = true
    backgroundImage.layer.borderColor = UIColor.white.cgColor
    backgroundImage.layer.borderWidth = 0.5
    to.insertSubview(backgroundImage, at: 0)

    let gradient = CAGradientLayer()
        let gradient1 = UIColor(red: 200/255, green: 100/255, blue: 5/255, alpha: 1).cgColor
        let gradient2 = UIColor(red: 1, green: 128/255, blue: 0, alpha: 1).cgColor
        gradient.colors = [gradient1, gradient2, gradient2, gradient1]

    gradient.locations = [0.0, 0.35, 0.65, 1.0]
    gradient.frame.size = to.frame.size
    backgroundImage.layer.addSublayer(gradient)
    backgroundImage.layer.cornerRadius = cornerRadius
}

但是,当我为 UIButton 设置新标题时,背景不会调整大小。当使文本比初始文本长时,文本将超出背景。

如何为 UIButton 制作带有渐变的背景大小?

【问题讨论】:

    标签: ios swift uibutton gradient


    【解决方案1】:

    为此,您需要创建一个自定义 UIButton 子类,并将 CAGradientLayer 设置为其图层类:

    class ExpandableGradientButton: UIButton {
    
    override class var layerClass: AnyClass {
        get {
                return CAGradientLayer.self
            }
        }
    }
    

    然后,您需要将函数更改为:

    @IBOutlet weak var expandableGradientButton: ExpandableGradientButton!
    ...
    public func addBackgroundAndGradient(to: UIView, gradient1: CGColor, gradient2: CGColor, cornerRadius: CGFloat = 5){
        let backgroundImage = UIImageView()
        backgroundImage.frame.size = to.frame.size
        backgroundImage.clipsToBounds = true
        backgroundImage.layer.borderColor = UIColor.white.cgColor
        backgroundImage.layer.borderWidth = 0.5
    
        let gradient1 = UIColor(red: 100/255, green: 140/255, blue: 2/255, alpha: 1).cgColor
        let gradient2 = UIColor(red: 123/255, green: 158/255, blue: 54.0/255.0, alpha: 1).cgColor
        if let butonLayer = to.layer as? CAGradientLayer
        {
            butonLayer.colors = [gradient1, gradient2, gradient2, gradient1]
            butonLayer.locations = [0.0, 0.35, 0.65, 1.0]
            butonLayer.cornerRadius = cornerRadius
        }
    }
    

    也就是说,你必须使用渐变层作为 UIButton 的层,它会自动调整大小。 注意:这也可以用于任何其他 UIView 子类,而不仅仅是 UIButton。

    【讨论】:

      猜你喜欢
      • 2014-07-01
      • 2016-03-23
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      相关资源
      最近更新 更多