首页 > 其他 > 详细

UILabel顶端对齐

时间:2016-09-26 12:32:27      阅读:222      评论:0      收藏:0      [点我收藏+]

比较一劳永逸的写法是对label添加一个分类

@interface UILabel (VerticalAlign)
/** 顶端对齐 */
-(void)alignTop;
/** 底部对齐 */
-(void)alignBottom;
@end
-(void)alignTop{
    CGSize fontSize = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;
    CGSize theStringSize = [self.text boundingRectWithSize:CGSizeMake(finalWidth, finalHeight)
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                attributes:@{NSFontAttributeName:self.font}
                                                   context:nil].size;
    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 sizeWithAttributes:@{NSFontAttributeName:self.font}];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;
    CGSize theStringSize = [self.text boundingRectWithSize:CGSizeMake(finalWidth, finalHeight)
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                attributes:@{NSFontAttributeName:self.font}
                                                   context:nil].size;
    int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
    for(int i=0; i<newLinesToPad; i++){
        self.text = [NSString stringWithFormat:@" \n%@",self.text];
    }
}

然后在使用时添加[myLabel alignTop]即可。
添加前

技术分享

使用后

技术分享

UILabel顶端对齐

原文:http://www.cnblogs.com/Apologize/p/5908537.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!