IOS UI篇—UILabel的文字頂部對齊


UILabel的文字頂部對齊

NOV 20TH, 2011

默認UILabel是垂直居中對齊的,如果你的UILabel高度有多行,當內容少的時候,會自動垂直居中。

如下圖所示(圖片來自stackoverflow):

比較郁悶的是,UILabel並不提供設置其垂直對齊方式的選項。所以如果你想讓你的文字頂部對齊,那么就需要自己想辦法了。 stackoverflow.com 上提供了幾種方法來達到頂部對齊的效果。

方法一

在顯示文字時,首先計算顯示當前的文字需要多寬和多高,然后將對應的UILabel的大小改變成對應的寬度和高度。此方法的相示意圖如下:

在顯示文字時,首先計算顯示當前的文字需要多寬和多高,然后將對應的UILabel的大小改變成對應的寬度和高度。此方法的相示意圖如下:

1
2 3 4 5 6 7 8 
CGSize maximumSize = CGSizeMake(300, 9999); NSString *dateString = @"The date today is January 1st, 1999"; UIFont *dateFont = [UIFont fontWithName:@"Helvetica" size:14]; CGSize dateStringSize = [dateString sizeWithFont:dateFont  constrainedToSize:maximumSize  lineBreakMode:self.dateLabel.lineBreakMode]; CGRect dateFrame = CGRectMake(10, 10, 300, dateStringSize.height); self.dateLabel.frame = dateFrame; 

方法二

此方法更加簡單粗暴,但是很有效。其方法是在文本后面加多一些\n。 需要注意的是,\n后還得加至少一個空格,否則多余的\n會被UILabel忽略。從這一點上看,UILabel似乎又過於“聰明”了。

該方法的示意圖如下:

該方法的代碼如下:

1
2 
for(int i=0; i<newLinesToPad; i++)  self.text = [self.text stringByAppendingString:@"\n "]; 

方法三

最正統的方法,利用objective-c的category特性,修改UILabel的繪制代碼。示例代碼如下:

1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 
// -- file: UILabel+VerticalAlign.h #pragma mark VerticalAlign @interface UILabel (VerticalAlign) - (void)alignTop; - (void)alignBottom; @end  // -- file: UILabel+VerticalAlign.m @implementation UILabel (VerticalAlign) - (void)alignTop {  CGSize fontSize = [self.text sizeWithFont:self.font];  double finalHeight = fontSize.height * self.numberOfLines;  double finalWidth = self.frame.size.width; //expected width of label  CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];  int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;  for(int i=0; i<newLinesToPad; i++)  self.text = [self.text stringByAppendingString:@"\n "]; }  - (void)alignBottom {  CGSize fontSize = [self.text sizeWithFont:self.font];  double finalHeight = fontSize.height * self.numberOfLines;  double finalWidth = self.frame.size.width; //expected width of label  CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];  int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;  for(int i=0; i<newLinesToPad; i++)  self.text = [NSString stringWithFormat:@" \n%@",self.text]; } @end 

我選了簡單暴力的方法二,你呢?

參考資料

http://stackoverflow.com/questions/1054558/how-do-i-vertically-align-text-within-a-uilabel 
https://discussions.apple.com/thread/1759957?threadID=1759957


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM