ios - How to change the text color in a CATextLayer in Swift -


i want change text color of catextlayer.

this not work

mytextlayer.textcolor 

since there no such property. got no response setting foreground color

textlayer.foregroundcolor = somecolor.cgcolor 

when text layer set 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 objective-c question catextlayer textcolor black answers there didn't seem make sense in situation.

since able solve problem reading documentation, sharing answer below.

general case

to set text color of catextlayer use

mytextlayer.foregroundcolor = uicolor.cyan.cgcolor 

as in

enter image description here

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 don't set color, default white both background , foreground.

using attributed string

according documentation,

the foregroundcolor property used when string property not nsattributedstring.

that why not able change color. need add color attributed string in 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) 

which gives

enter image description here


Comments