ios - 如何将颜色渐变应用于 UILabel 的背景?

标签 ios swift uilabel gradient

例如,标签的左侧为灰色,右侧为蓝色。我希望左侧的颜色为灰色,但随着向右的颜色变深,直到标签的右侧完全变成蓝色。有没有办法做到这一点,而无需在线寻找图像并将标签的背景颜色设置为图像?

最佳答案

您可以将 UILabel 添加到 UIView 中,并将渐变层添加到该 UIView 中。 要添加渐变层,您可以使用以下代码。

let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
let gradient = CAGradientLayer()

gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]

view.layer.insertSublayer(gradient, at: 0)

您也可以引用这个question

关于ios - 如何将颜色渐变应用于 UILabel 的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51531015/

相关文章:

iphone - 检查电子邮件是否有效

ios - 自定义 transitionFromViewController 抛出错误

macos - 永久修改 RGB Gamma 表

iOS 标签不会在 Swift 中使用函数更新文本

objective-c - iPhone iOS UILabel 如何仅自定义 UITableView 详细文本标签的文本颜色?

ios - 如何在swift 3中压缩数据?

ios - WatchKit - iPhone 不可用屏幕

ios - 操作按钮在前台显示应用程序

ios - 如何创建一个里面有 2 个数组的字典?

ios - 将较暗的透明背景设置为图像上的标签