您可以使用sizeWithAttributes:
来获取文本前半部分的大小,然后调整UILabel
的位置。
NSString* firstHalf = [[label.text componentsSeparatedByString:@":"] objectAtIndex:0];
CGSize firstHalfSize = [firstHalf sizeWithAttributes:textAttributes];
CGRect labelFrame = label.frame;
labelFrame.origin.x = center.x-firstHalfSize.width;
label.frame = labelFrame;
这将在中心设置“:”的起始位置。如果你想要把这个角色的中间的中心,您可以添加以下内容:
NSString* firstHalf = [[label.text componentsSeparatedByString:@":"] objectAtIndex:0];
CGSize firstHalfSize = [firstHalf sizeWithAttributes:textAttributes];
CGSize charSize = [@":" sizeWithAttributes:textAttributes];
CGRect labelFrame = label.frame;
labelFrame.origin.x = self.view.bounds.size.width/2-firstHalfSize.width-charSize.width/2;
label.frame = labelFrame;
你也可以修改固有大小和文本对齐方式(左或右)在标签内正确居中的文本。也许可以使用'NSParagraphStyle'中的'headIntent'和'tailIndent'。也可以使用':'作为制表符列结束符,并在段落样式中用'NSTextTab'做魔术。 – Sulthan