How to change the text color in a CATextLayer in Swift
I want to change the text color of a CATextLayer.
This does not work
since there is no such property. I also got no response by setting the foreground color
textLayer.foregroundColor = someColor.CGColor
when the text layer is set up as follows
let myAttribute = [ NSFontAttributeName: UIFont(name: mongolFontName, size: fontSize )! ] let attrString = NSMutableAttributedString(string: textLayer.displayString, attributes: myAttribute ) textLayer.frame = myFrame textLayer.string = attrString
I have seen the Objective-C question CATextLayer textcolor is always black but the answers there didn’t seem to make sense in my situation.
Since I was able to solve my problem by reading the documentation, I am sharing the answer below.
Solutions Collect From Internet About “How to change the text color in a CATextLayer in Swift”
To set the text color of a CATextLayer use
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)
If you don’t set the color, the default is white for both the background and the foreground.
Using an Attributed String
According to the documentation,
foregroundColorproperty is only used when the
stringproperty is not an
That is why you were not able to change the color. You need to add the color to the attributed string in this case.
// Attributed string let myAttributes = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 30.0)! , // font NSForegroundColorAttributeName: 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)
- Pedometer in the Background
- Generic function and attribute with Equatable and Printable as parameters in Swift
- Number of characters in an NSString
- Call instance method from class method
- COMET (server push to client) on iPhone
- How to scale/position nodes Swift SpriteKit? Custom View?
- Adding Linker Flags in Xcode
- Delivering MDM DeviceLock Payload
- How to generate NSManagedObject classes in Objective C instead of Swift?
- Restarting OSX app programmatically
- Behavior changes for updateViewConstraints in iOS 8
- App rejected, but I don't use UDID
- What does it mean when you check on “Recursive” in Header Search Paths
- iPhone App :show direction using Map
- Swift SpriteKit playing audio in the background