出自:http://blog.csdn.net/braver_smile/article/details/42966427
有的时候可能会用到这样的布局效果,label固定尺寸,但是text可能略小,这个时候系统提供的方法只能垂直居中,靠左,靠右,水平居中。但是都在垂直方向上,可能满足不了我们的要求。这里提出了一种方法,当然还有其他的方法,例如用drawInRect重绘。
贴出示例代码如下:
#import "ViewController.h"
#import "UILabel+VerticalAlign.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UILabel *label = [[UILabelalloc] initWithFrame:CGRectMake(50,200, 200, 200)];
[label setText:@"hello"];
[label setTextColor:[UIColorblackColor]];
[label setBackgroundColor:[UIColorgreenColor]];
[label alignTop];
[self.viewaddSubview:label];
}
#import "UILabel+VerticalAlign.h"
@implementation UILabel (VerticalAlign)
-(void)alignTop
{
CGSize fontSize;
NSDictionary *attribute =@{NSFontAttributeName:self.font};
fontSize = [self.textboundingRectWithSize:self.frame.sizeoptions:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributecontext:nil].size;
fontSize.height = fontSize.height+1;
self.numberOfLines =self.frame.size.height / fontSize.height;
NSLog(@"%ld", (long)self.numberOfLines);
double finalHeight = fontSize.height *self.numberOfLines;
CGSize theStringSize =fontSize;
int newLines=(finalHeight - theStringSize.height)/ fontSize.height;
for(int i=0; i
self.text =[self.textstringByAppendingString:@"\n "];
}
-(void)alignBottom
{
CGSize fontSize;
NSDictionary *attribute =@{NSFontAttributeName:self.font};
fontSize = [self.textboundingRectWithSize:self.frame.sizeoptions:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributecontext:nil].size;
fontSize.height = fontSize.height+1;
self.numberOfLines =self.frame.size.height / fontSize.height;
double finalHeight = fontSize.height *self.numberOfLines;
CGSize theStringSize =fontSize;
int newLinesToPad =(finalHeight - theStringSize.height)/ fontSize.height;
for(int i=0; i
self.text =[NSStringstringWithFormat:@" \n%@",self.text];
}
@end