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
The red one is UILabel
, the green one is CALayer. I want to know how to vertical align the text in
CALayer, as the
UILabel` shows.
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.