【问题标题】:how to set gradient layer width to be the same as button width?如何将渐变层宽度设置为与按钮宽度相同?
【发布时间】:2019-12-12 14:37:44
【问题描述】:

我是 iOS 开发的新手,我想使用这个可设计的类来制作渐变圆形按钮

@IBDesignable
class GradientButton: UIButton {
    let gradientLayer = CAGradientLayer()

    @IBInspectable
    var topGradientColor: UIColor? {
        didSet {
            setGradient(topGradientColor: topGradientColor, bottomGradientColor: bottomGradientColor)
        }
    }

    @IBInspectable
    var bottomGradientColor: UIColor? {
        didSet {
            setGradient(topGradientColor: topGradientColor, bottomGradientColor: bottomGradientColor)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        updateCornerRadius()
    }

    @IBInspectable var fullRounded: Bool = false {
        didSet {
            updateCornerRadius()
        }
    }



    @IBInspectable var cornerRadiusOfButton : CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadiusOfButton
        }
    }

    func updateCornerRadius() {
        layer.cornerRadius = fullRounded ? (frame.size.height / 2) : cornerRadiusOfButton
    }


    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            layer.borderColor = uiColor.cgColor
        }
        get {
            guard let color = layer.borderColor else { return nil }
            return UIColor(cgColor: color)
        }
    }

    private func setGradient(topGradientColor: UIColor?, bottomGradientColor: UIColor?) {
        if let topGradientColor = topGradientColor, let bottomGradientColor = bottomGradientColor {
            gradientLayer.frame = bounds
            gradientLayer.colors = [topGradientColor.cgColor, bottomGradientColor.cgColor]
            gradientLayer.borderColor = layer.borderColor
            gradientLayer.borderWidth = layer.borderWidth
            gradientLayer.cornerRadius = layer.cornerRadius
            layer.insertSublayer(gradientLayer, at: 0)
        } else {
            gradientLayer.removeFromSuperlayer()
        }
    }
}

但结果如下:

您可以看到渐变层按钮的宽度不正确。

这是我使用的约束布局:

我希望那个渐变层和原始按钮的宽度一样,我怀疑问题出在这一行

gradientLayer.frame = bounds

但不幸的是,我不知道如何在@IBDesignable 类中以编程方式将渐变层宽度设置为与原始按钮相同的大小

你能帮我解决这个问题吗?提前谢谢

【问题讨论】:

  • 尝试在 gradientLayer.frame = bounds gradientLayer.masksToBounds=true 之后添加以下内容

标签: ios swift uibutton ibdesignable


【解决方案1】:

GradientButton 中覆盖layoutSubviews 并将gradientLayer frame 更新为,

override func layoutSubviews() {
    super.layoutSubviews()

    self.gradientLayer.frame = bounds
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多