Skip to content

Instantly share code, notes, and snippets.

@mluton
Created April 5, 2013 23:49
Show Gist options
  • Save mluton/5323538 to your computer and use it in GitHub Desktop.
Save mluton/5323538 to your computer and use it in GitHub Desktop.
Put an NSAttributedString into a CATextLayer. This works in iOS 5.
CATextLayer *textLayer = [CATextLayer layer];
textLayer.backgroundColor = [UIColor whiteColor].CGColor;
textLayer.frame = CGRectMake(20, 20, 200, 100);
textLayer.contentsScale = [[UIScreen mainScreen] scale];
CTFontRef fontFace = CTFontCreateWithName((__bridge CFStringRef)(@"HelfaSemiBold"), 24.0, NULL);
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:(__bridge id)fontFace forKey:(NSString*)kCTFontAttributeName];
[attributes setObject:[UIColor blackColor] forKey:(NSString*)kCTForegroundColorAttributeName];
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"Lorem Ipsum" attributes:attributes];
textLayer.string = attrStr;
[self.view.layer addSublayer:textLayer];
@koedal
Copy link

koedal commented Apr 15, 2014

I had to change

[attributes setObject:[UIColor blackColor] forKey:(NSString*)kCTForegroundColorAttributeName];

into

[attributes setObject:(id)[UIColor blackColor].CGColor forKey:(NSString*)kCTForegroundColorAttributeName];

in order for this to work for me.

@Akhrameev
Copy link

Thank you so much! That helped me, too!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment