2014-05-07 33 views
0

我想对齐UILabel中的UILabel或NSAttributedString,以便指定的字符始终与屏幕中心对齐。如何通过单个字符对齐字符串UILabel/NSAttributedString

一种方法是使用两个标签。一个用于指定的字符和左侧的子字符串,并使其右对齐。第二个用于指定字符的子字符串。

我想知道是否有一种方法来简化过程(现在与全能的NSAttributedString)。 或者也许用NSDateFormatter。

示例用法:以时间格式(例如“12:40”,“9:14”,“3:04 PM”)设置“:”始终居中屏幕(或任何其他任何东西其他)。无论字体/次数/ AM-PM符号如何。

感谢您的帮助。

回答

0

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

你也可以修改固有大小和文本对齐方式(左或右)在标签内正确居中的文本。也许可以使用'NSParagraphStyle'中的'headIntent'和'tailIndent'。也可以使用':'作为制表符列结束符,并在段落样式中用'NSTextTab'做魔术。 – Sulthan