利用objective-c的category特性,修改UILabel的绘制代码。示例代码如下
#import <UIKit/UIKit.h> @interface UILabel (VerticalAlign) - (void)alignTop; - (void)alignBottom; @end
#import "UILabel+VerticalAlign.h"
@implementation UILabel (VerticalAlign)
- (void)alignTop {
CGSize fontSize = [self.text sizeWithFont:self.font];
int textOfLine = self.frame.size.height/fontSize.height;
double finalHeight = fontSize.height * textOfLine;
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];
int textOfLine = self.frame.size.height/fontSize.height;
double finalHeight = fontSize.height * textOfLine;
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
使用
[你的label名 alignBottom];
调用
- - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - -
以下是自动换行
- - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - -- - - - - - - - - - - -
(省略定义加载relase label的代码)
CGSize maximumLabelSize = CGSizeMake(150,99999); //先设置一个最大限度
CGSize expectedLabelSize = [lable.text sizeWithFont:lable.font constrainedToSize:maximumLabelSize lineBreakMode:lable.lineBreakMode]; //设置自动换行,constrainedToSize设置可以接收String的最大值
label.frame = CGRectMake(20, 20, 150, expectedLabelSize.height);