如何在Swift中更改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总是黑色的,但是那里的答案在我的情况下似乎没有意义。

由于我通过阅读文档能够解决我的问题,因此我在下面分享了答案。

一般情况

设置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) 

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

使用属性string

根据文件 ,

foregroundColor属性仅在string属性不是NSAttributedString

这就是为什么你无法改变颜色。 在这种情况下,您需要将颜色添加到属性string中。

 // 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

Swift 3解决scheme (但与其他语言相同的问题)。

秘诀在于添加titleLayer.display()。

 let titleLayer = CATextLayer() titleLayer.string = "My text" titleLayer.frame = CGRect(x:0, y:O, width:UIScreen.main.bounds.width, height:UIScreen.main.bounds.width.height) titleLayer.font = CGFont("HelveticaNeue-UltraLight" as CFString)! titleLayer.fontSize = 100 titleLayer.alignmentMode = kCAAlignmentCenter titleLayer.backgroundColor = UIColor.blue.cgColor titleLayer.foregroundColor = UIColor.cyan.cgColor titleLayer.display()