Andrea Andrea - 1 year ago 115
Swift Question

CATextLayer NSBackGroundColorAttributeName is there a way to make it works?

I'm trying to make a

the attribute in an attributed string?

let mutableAttributed = NSMutableAttributedString(string: text , attributes: [
NSForegroundColorAttributeName : UIColor.redColor(),
NSBackgroundColorAttributeName : UIColor.whiteColor(),
NSFontAttributeName :UIFont.systemFontOfSize(12)
let textLayer = CATextLayer()
textLayer.needsDisplayOnBoundsChange = true
textLayer.string = mutableAttributed
textLayer.bounds.size = CGSizeMake(200,200)

But it simply doesn't work, reading Stack I've found a reasonable answer but is pretty old, and it doesn't seems to be fully clear, if from iOS6 it should support it or not.

Answer Source

The answer you pointed to is right. CATextLayer is very primitive and doesn't support this feature. Luckily, there is no need to use core text either; you can now use TextKit and just draw the string directly (and don't use CATextLayer at all).

class MyTextLayer : CALayer {
    @NSCopying var string : NSAttributedString?

    override func drawInContext(ctx: CGContext) {
            options: .UsesLineFragmentOrigin, context: nil)