1

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.

Community
  • 1
  • 1
Andrea
  • 26,120
  • 10
  • 85
  • 131

1 Answers1

2

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()
    }
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Sorry, I was just trying to assemble code from the original one, of course in the original I was setting the right property. I've update the answer. Thanks – Andrea Jul 03 '16 at 14:59
  • Added code showing how to build a CALayer that draws its own attributed text. – matt Jul 03 '16 at 15:13
  • Actually I can' t use a normal TextKit View, because I'm adding layers over a video composition. As far as I remember Apple explicitly say to do not use UIView's layer. Now I'm thinking to use your code or just enumerating string attributes, to set just the layer background. Many thanks – Andrea Jul 03 '16 at 15:36
  • 2
    The point is this. Back in the CATextLayer days, you had to use CoreText (and NSAttributedString was extremely hard to use; it wasn't really a native type on iOS). But an NSAttributedString nowadays knows how to draw itself (as my code shows). When it does that, you're using TextKit; to put another way, TextKit is the innovation that makes this possible, and that didn't happen until after the discussion you were looking at before. – matt Jul 03 '16 at 16:42