基于YYtext自动计算lable的高度或宽度

一:使用方式


二:实现方法

BasisYYLableCalculationHeightAndWidth.h

#import#import@interface BasisYYLableCalculationHeightAndWidth : NSObject

/**

*  @param message lable.text

*  @param lable (YYLabel *)label

*  @return lable的高度

*/

+ (CGFloat)getLableHeight:(NSString *)message yyLabel:(YYLabel *)lable lineSpacing:(CGFloat)lineSpace stringFont:(UIFont *)font;

/**

*  @param message lable.text

*  @param lable (YYLabel *)label

*  @return lable的宽度

*/

+ (CGFloat)getLableWidth:(NSString *)message yyLabel:(YYLabel *)lable stringFont:(UIFont *)font;

@end

BasisYYLableCalculationHeightAndWidth.m

#import "BasisYYLableCalculationHeightAndWidth.h"#import@implementation BasisYYLableCalculationHeightAndWidth

+ (CGFloat)getLableHeight:(NSString *)message yyLabel:(YYLabel *)lable lineSpacing:(CGFloat)lineSpace stringFont:(UIFont *)font;

{

    NSMutableAttributedString *introText = [[NSMutableAttributedString alloc] initWithString:message];

    introText.yy_font = font;

    introText.yy_lineSpacing = lineSpace;//行间距

    lable.attributedText = introText;

    CGSize introSize = CGSizeMake(lable.frame.size.width, CGFLOAT_MAX);

    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:introSize text:introText];

    lable.textLayout = layout;

    CGFloat introHeight = layout.textBoundingSize.height;

    return introHeight;

}

+ (CGFloat)getLableWidth:(NSString *)message yyLabel:(YYLabel *)lable stringFont:(UIFont *)font;

{

    NSMutableAttributedString *introText = [[NSMutableAttributedString alloc] initWithString:message];

    introText.yy_font = font;

    lable.attributedText = introText;

    CGSize introSize = CGSizeMake(CGFLOAT_MAX, lable.frame.size.height);

    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:introSize text:introText];

    lable.textLayout = layout;

    CGFloat introWidth = layout.textBoundingSize.width;

    return introWidth;

}

@end

感谢YYKit作者:郭曜源

传送门:

            YYKit

            YYText

你可能感兴趣的:(基于YYtext自动计算lable的高度或宽度)