从0开始架构一个IOS程序——iOS 根据文字的长度来动态设置UILabel的大小

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zl18603543572/article/details/79306746

UIlabel根据文字的长度来动态设置的大小

#import <Foundation/Foundation.h>

@interface SINALabelUtils : NSObject


//根据文字内容来动态设置label的宽与高
//参数一 tagLabel 动态设置的label
//参数二 tagString 需要测量的文字的长度
+(UILabel *) updateLabel:(UILabel*) tagLabel andWithString:(NSString*)tagString;

//根据文字内容来动态设置label的宽与高
//参数一 tagLabel 动态设置的label
//参数二 tagString 需要测量的文字的长度
//参数三 fontSize  需要设置的文字的大小
+(UILabel *) updateLabel:(UILabel*) tagLabel andWithString:(NSString*)tagString andWithTextSize:(NSInteger) fontSize;
//根据文字内容来动态设置label的宽与高
//参数一 tagLabel 动态设置的label
//参数二 tagString 需要测量的文字的长度
//参数三 tagWidth  label 可设置的最大宽度
//参数四 tagHeight label 可设置的最大高度
//参数五 fontSize  需要设置的文字的大小
+(UILabel *)updateLabel:(UILabel *)tagLabel andWithString:(NSString *)tagString andWithTagWidth:(NSInteger) tagWidth andWithTagHeight:(NSInteger) tagHeight andWithTagFontSize:(NSInteger)fontSize;
@end
#import "SINALabelUtils.h"

@implementation SINALabelUtils


+(UILabel *)updateLabel:(UILabel *)tagLabel andWithString:(NSString *)tagString{
    return [[self class] updateLabel:tagLabel andWithString:tagString andWithTagWidth:[UIScreen mainScreen].bounds.size.width andWithTagHeight:[UIScreen mainScreen].bounds.size.height andWithTagFontSize:16];
}

+(UILabel *)updateLabel:(UILabel *)tagLabel andWithString:(NSString *)tagString andWithTextSize:(NSInteger)fontSize{
    return [[self class] updateLabel:tagLabel andWithString:tagString andWithTagWidth:[UIScreen mainScreen].bounds.size.width andWithTagHeight:[UIScreen mainScreen].bounds.size.height andWithTagFontSize:fontSize];
}

+(UILabel *)updateLabel:(UILabel *)tagLabel andWithString:(NSString *)tagString andWithTagWidth:(NSInteger) tagWidth andWithTagHeight:(NSInteger) tagHeight andWithTagFontSize:(NSInteger)fontSize{

    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],};
    CGSize textSize = [tagString boundingRectWithSize:CGSizeMake(tagWidth, tagHeight) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;;
    tagLabel.numberOfLines=0;
    //重置label的frame 主要是重设label的宽度与调试
    tagLabel.frame=CGRectMake(tagLabel.frame.origin.x, tagLabel.frame.origin.y, textSize.width, textSize.height);
    return tagLabel;
}

@end

猜你喜欢

转载自blog.csdn.net/zl18603543572/article/details/79306746