[英]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.