ios - 如何在 Swift 中更改 CATextLayer 中的文本颜色

标签 ios swift textcolor catextlayer

我想更改 CATextLayer 的文本颜色。

这行不通

myTextLayer.textColor

因为没有这样的属性。我设置前景色也没有反应

textLayer.foregroundColor = someColor.CGColor

当文字层设置如下

let myAttribute = [ NSFontAttributeName: UIFont(name: mongolFontName, size: fontSize )! ]
let attrString = NSMutableAttributedString(string: textLayer.displayString, attributes: myAttribute )
textLayer.frame = myFrame
textLayer.string = attrString

我看到了 Objective-C 问题 CATextLayer textcolor is always black但是那里的答案在我的情况下似乎没有意义。

因为我能够通过阅读 documentation 解决我的问题,我在下面分享答案。

最佳答案

一般情况

要设置 CATextLayer 使用的文本颜色

myTextLayer.foregroundColor = UIColor.cyan.cgColor

如在

enter image description here

let myTextLayer = CATextLayer()
myTextLayer.string = "My text"
myTextLayer.backgroundColor = UIColor.blue.cgColor
myTextLayer.foregroundColor = UIColor.cyan.cgColor
myTextLayer.frame = myView.bounds
myView.layer.addSublayer(myTextLayer)

如果不设置颜色,背景和前景默认都是白色。

使用属性字符串

根据documentation ,

The foregroundColor property is only used when the string property is not an NSAttributedString.

这就是您无法更改颜色的原因。在这种情况下,您需要将颜色添加到属性字符串。

// Attributed string
let myAttributes = [
    NSAttributedStringKey.font: UIFont(name: "Chalkduster", size: 30.0)! , // font
    NSAttributedStringKey.foregroundColor: UIColor.cyan                    // text color
]
let myAttributedString = NSAttributedString(string: "My text", attributes: myAttributes )

// Text layer
let myTextLayer = CATextLayer()
myTextLayer.string = myAttributedString
myTextLayer.backgroundColor = UIColor.blue.cgColor
//myTextLayer.foregroundColor = UIColor.cyan.cgColor // no effect
myTextLayer.frame = myView.bounds
myView.layer.addSublayer(myTextLayer)

给出

enter image description here

答案已更新为 Swift 4

关于ios - 如何在 Swift 中更改 CATextLayer 中的文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835130/

相关文章:

java - TabHost (Android) 中的 "Show More"选项与 iO 中一样

c# - 创建 UIButton 时不显示标题文本

ios - 首次加载到 Swift 中的 UICollectionView 时,视差效果略显不稳定

SwiftUI - 如何更改文本字段的文本颜色?

ios - UIView 上下移动

ios - 如何隐藏 UILabel Swift : Label is creating space in table view controller when Label is set to hidden

ios - 无法以字符串格式获取日期

ios - 应用剪切路径后,如何确定点是否位于路径内部?

android - edittext 的 textColor 和 textAppearance

android 数字选择器文本颜色