您可以使用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