ode中默认的UILabel是垂直居中对齐的,如果你的UILabel高度有多行,当内容少的时候,会自动垂直居中。
比较郁闷的是,UILabel并不提供设置其垂直对齐方式的选项。所以如果你想让你的文字顶部对齐,那么就需要自己想办法了。
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;
for(int i=0; i<newLinesToPad; i++)
self.text =[self.text stringByAppendingString:@"
"];
// -- file: UILabel+VerticalAlign.h
#pragma mark VerticalAlign
@interfaceUILabel(VerticalAlign)
-(void)alignTop;
-(void)alignBottom;
@end
// -- file: UILabel+VerticalAlign.m
@implementationUILabel(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:@"
"];
}
-(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:@"
%@",self.text];
}
@end