在顯示文字時,首先計算顯示當前的文字須要多寬和多高,而後將對應的UILabel的大小改變成對應的寬度和高度。此方法的相示意圖以下:objective-c
在顯示文字時,首先計算顯示當前的文字須要多寬和多高,而後將對應的UILabel的大小改變成對應的寬度和高度。此方法的相示意圖以下:ui
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彷佛又過於「聰明」了。spa
該方法的示意圖以下:code
該方法的代碼以下:orm
1
2 |
for(int i=0; i<newLinesToPad; i++) self.text = [self.text stringByAppendingString:@"\n "]; |
最正統的方法,利用objective-c的category特性,修改UILabel的繪製代碼。示例代碼以下:blog
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 |