Search code examples
swiftcalayernsattributedstring

CATextLayer NSBackGroundColorAttributeName is there a way to make it works?


I'm trying to make a CATextLayer accept NSBackGroundColorAttributeName 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.


Solution

  • 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) {
            super.drawInContext(ctx)
            UIGraphicsPushContext(ctx)
            string?.drawWithRect(self.bounds,
                options: .UsesLineFragmentOrigin, context: nil)
            UIGraphicsPopContext()
        }
    }