实现原理:当该label不足以达到要求的高度时,居上对齐时在页末补“ 空格”,居下对齐时在页首补“空格 ”
UILabel+VerticalAlign.h
@interface UILabel(VerticalAlign) -(void)alignTop; -(void)alignBottom; @end
UILabel+VerticalAlign.m
@implementation UILabel(VerticalAlign) -(void)alignTop { CGSize fontSize =[self.text sizeWithFont:self.font]; double finalHeight = self.frame.size.height;//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