how to set CATextLayer text vertical position?

NOrder picture NOrder · Aug 8, 2013 · Viewed 11.2k times · Source

I create UILabel and CATextLayer in my app using following code

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 90, 20, 20)];
    self.textLabel.text = @"1";
    self.textLabel.font = [UIFont systemFontOfSize:12];
    self.textLabel.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.textLabel];

    self.textLayer = [CATextLayer layer];
    [self.textLayer setString:@"1"];
    [self.textLayer setFont:(__bridge CFTypeRef)([UIFont systemFontOfSize:12])];
    self.textLayer.backgroundColor = [UIColor greenColor].CGColor;
    self.textLayer.frame = CGRectMake(70, 90, 50, 20);
    [self.view.layer addSublayer:self.textLayer];
}

and the result is

enter image description here

The red one is UILabel, the green one is CALayer. I want to know how to vertical align the text inCALayer, as theUILabel` shows.

Answer

BonanzaDriver picture BonanzaDriver · Jan 13, 2016

Actually, this is what works for me:

self.layer.addSublayer(textLayer)
textLayer.font = font
textLayer.fontSize = font.pointSize
textLayer.frame = CGRectMake(self.layer.bounds.origin.x, ((self.layer.bounds.height - textLayer.fontSize) / 2) - lineWidth, self.layer.bounds.width, self.layer.bounds.height)
textLayer.alignmentMode - kCAAlignmentCenter
textLayer.contentsScale = UIScreen.mainScreen().scale

LineWidth is what I use to "frame" my bounding area. This keeps my text centered vertically and horizontally.