How to change the text color in a CATextLayer in Swift

后端 未结 2 1627
无人及你
无人及你 2021-01-13 09:12

I want to change the text color of a CATextLayer.

This does not work

myTextLayer.textColor

since there is no such property. I also

2条回答
  •  时光说笑
    2021-01-13 09:35

    General Case

    To set the text color of a CATextLayer use

    myTextLayer.foregroundColor = UIColor.cyan.cgColor
    

    as in

    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,

    The foregroundColor property is only used when the string property is not an NSAttributedString.

    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 = [
        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)
    

    which gives

    Answer updated to Swift 4

提交回复
热议问题