【问题标题】:Button stretch when gradient applied应用渐变时按钮拉伸
【发布时间】:2016-07-24 08:07:37
【问题描述】:

首先,我为情节提要中的按钮设置了约束。然后,我在代码中对其进行了编辑以使其看起来不错。 当我将渐变功能应用于按钮时,它会变得比以前大。你如何解决这个问题?

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)
    }
}

我只是将它应用在一个按钮上,然后.. Here is the pic...

现在看起来像这样......渐变边界没有做任何事情It goes way outside framePLZPLZPLZ 尝试帮助我 :) 到目前为止我很感激你的帮助

【问题讨论】:

    标签: ios swift button gradient


    【解决方案1】:

    self.layer.masksToBounds = true 添加到函数中。这意味着您添加的子图层不会在按钮的原始框架之外绘制

    编辑: 如果您还想要阴影,则需要将 self.layer.masksToBounds 设置为 false,因为它也会剪切阴影。

    试试gradient.frame = self.layer.bounds 可以吗?

    【讨论】:

    • 它说 CALAyer 类型的值没有成员 clipsToBounds...我该怎么办
    • 实际上渐变是存在的,但是我添加的阴影在 .MaskstoBounds 之后消失了...我做了 button.layer.borderWidth = 2.9 button.layer.shadowRadius=1.0 buttonLayer.shadowOffset = CGSizeMake(0 ,3) 整个阴影消失了,大概是因为它不适合原始框架……那我该如何保留它
    • 基本上它可以限制大小......但是按钮阴影消失了......你如何解决这个问题
    • 如果没有 maskToBOunds,它会恢复正常,如果你按照上面的图片链接,但有阴影..请帮助 :) 我很感激