讓UILabel的文字頂部對齊

原文章連接:http://blog.devtang.com/2011/11/20/set-uilabel-text-align-top/objective-c

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

以下圖所示(圖片來自stackoverflow):ui

比較鬱悶的是,UILabel並不提供設置其垂直對齊方式的選項。因此若是你想讓你的文字頂部對齊,那麼就須要本身想辦法了。 stackoverflow.com 上提供了幾種方法來達到頂部對齊的效果。spa

方法一

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

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

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彷佛又過於「聰明」了。blog

該方法的示意圖以下:圖片

該方法的代碼以下:get

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

方法三

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

// -- 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

相關文章
相關標籤/搜索