给UILabel的文字添加垂直对齐的方式

2016-07-21  本文已影响0人  LeeTrombone

UILabel的文字默认是垂直居中显示的,而且UILabel并没有为我们提供设置垂直对齐方式的选项,所以要自己想办法了。
我的办法是给UILabel添加一个Category,来修改UILabel的绘制。话不多说上代码:

//  UILabel+VerticalAlignment.h
#import <UIKit/UIKit.h>

@interface UILabel (VerticalAlignment)

// 文字顶部对齐
- (void)textAlignmentTop;

// 文字底部对齐
- (void)textAlignmentBottom;

@end
//  UILabel+VerticalAlignment.m
#import "UILabel+VerticalAlignment.h"

@implementation UILabel (VerticalAlignment)

- (void)textAlignmentTop {
    self.numberOfLines = 0;
    CGSize fontSize = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
    double finalWidth = self.frame.size.width;
    CGSize maximumSize = CGSizeMake(finalWidth, CGFLOAT_MAX);
    CGRect stringSize = [self.text boundingRectWithSize:maximumSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil];
    int lines = (self.frame.size.height - stringSize.size.height) / fontSize.height;
    for (int i = 0; i < lines; i++) {
        self.text = [self.text stringByAppendingString:@"\n"];
    }
}

- (void)textAlignmentBottom {
    self.numberOfLines = 0;
    CGSize fontSize = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
    double finalWidth = self.frame.size.width;
    CGSize maximumSize = CGSizeMake(finalWidth, CGFLOAT_MAX);
    CGRect stringSize = [self.text boundingRectWithSize:maximumSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil];
    int lines = (self.frame.size.height - stringSize.size.height) / fontSize.height;
    for (int i = 0; i < lines; i++) {
        self.text = [NSString stringWithFormat:@" \n%@",self.text];
    }
}

@end
上一篇下一篇

猜你喜欢

热点阅读