ios - CAGradientLayer 没有跨越我按钮的整个宽度 - xcode

标签 ios swift xcode cagradientlayer

我是 xcode 的新手,我在按钮上放置了一个渐变层,但它没有填满整个宽度。我不确定我做错了什么。我的代码在这里以及它如何呈现的屏幕截图。

let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.btnSavePhoto.bounds
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha:1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha:1.0).CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.btnSavePhoto.layer.addSublayer(gradientLayer)

enter image description here

最佳答案

您的按钮似乎稍后会更改其大小(由于自动调整掩码或约束),但 gradientLayer 保持原始(较小)大小。这是由于图层不会自动调整大小这一事实引起的。 您可以创建一个自定义 UIButton 子类,该子类将在 layoutSubviews 方法中更新自定义层的大小。 或者您可以创建一个自定义图层子类,尽管它还需要创建一个 UIButton 子类,如以下问题所述:CALayers didn't get resized on its UIView's bounds change. Why?

关于ios - CAGradientLayer 没有跨越我按钮的整个宽度 - xcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39128498/

相关文章:

ios - 应用内购买自动续订与不可续订?

swift - 自定义 UITableViewCell 只有两个创建的类之一没有初始化错误。 swift

swift - 错误域=NSURLErrorDomain 代码=-999 "cancelled"Xcode

ios - 链接器命令失败并显示退出代码(没有此类模块)

ios - SKPaymentTransaction 的 originalTransaction.transactionReceipt nil 用于恢复非消耗品

ios - UITableViewCell UIView 颜色在类加载时不会立即更改

ios - 子串字符串并在它们之间进行比较

macos - Swift NSStackView : Learn By Doing. 我做错了什么?

Swift - 带有 xib 文件的自定义 View ,IBOutlet 为 nil

ios - 有关此 View 的信息