UILabel居上对齐居下对齐类别扩展

实现原理:当该label不足以达到要求的高度时,居上对齐时在页末补“\n空格”,居下对齐时在页首补“空格\n”

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:@"\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; i++)
        self.text =[NSString stringWithFormat:@" \n%@",self.text];
}
@end

 

posted @ 2014-04-19 15:10  MittyoO  阅读(354)  评论(0编辑  收藏  举报