美文网首页
iOS - UILabel中的文字置顶或置底

iOS - UILabel中的文字置顶或置底

作者: th先生 | 来源:发表于2017-10-13 14:12 被阅读0次

通过一个类别,轻松实现。代码如下:

.h

#import <UIKit/UIKit.h>

@interface UILabel (Vertical)

- (void)alignTop;

- (void)alignBottom;

@end

.m

#import "UILabel+Vertical.h"

@implementation UILabel (Vertical)

-(void)alignTop
{
    // 对应字号的字体一行显示所占宽高
    CGSize fontSize = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
    // 多行所占 height*line
    double height = self.frame.size.height;
    // 显示范围实际宽度
    double width = self.frame.size.width;
    // 对应字号的内容实际所占范围
    CGSize stringSize = [self.text boundingRectWithSize:CGSizeMake(width, height) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:self.font} context:nil].size;
    // 剩余空行
    NSInteger line = (height - stringSize.height) / fontSize.height;
    // 用回车补齐
    for (int i = 0; i < line; i++) {
        
        self.text = [self.text stringByAppendingString:@"\n "];
    }
}
-(void)alignBottom
{
    CGSize fontSize = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
    double height = fontSize.height*self.numberOfLines;
    double width = self.frame.size.width;
    CGSize stringSize = [self.text boundingRectWithSize:CGSizeMake(width, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil].size;
    
    NSInteger line = (height - stringSize.height) / fontSize.height;
    // 前面补齐换行符
    for (int i = 0; i < line; i++) {
        self.text = [NSString stringWithFormat:@" \n%@", self.text];
    }
}

@end

相关文章

网友评论

      本文标题:iOS - UILabel中的文字置顶或置底

      本文链接:https://www.haomeiwen.com/subject/sgezyxtx.html