繁体   English   中英

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

[英]How to change the text color in a CATextLayer in Swift

我想更改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)

如果未设置颜色,则背景和前景的默认值均为白色。

使用归因字符串

根据文件

foregroundColor属性仅在string属性不是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)

这使

在此输入图像描述

答案已更新至Swift 4

Swift 3解决方案 (但与其他语言相同)。

秘诀在于添加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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM