我想更改 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
如在
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 thestring
property is not anNSAttributedString
.
这就是您无法更改颜色的原因。在这种情况下,您需要将颜色添加到属性字符串。
// 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)
给出
答案已更新为 Swift 4
关于ios - 如何在 Swift 中更改 CATextLayer 中的文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835130/