iOS UILable 自适应宽度和高度

联系人:石虎QQ: 1224614774  昵称:嗡嘛呢叭咪哄

//一行代码实现自适应 UIlable 的宽度效果:


iOS UILable 自适应宽度和高度_第1张图片

#import"UILabel+Extension.h"

- (void)viewDidLoad {

[superviewDidLoad];

//直接引用分类功能

[UILabelcreateLabelWithContent:@"10011111111110"addView:self.viewlableX:10lableY:111lableH:30fontSize:16backgroundColor:[UIColorredColor]textColor:[UIColorblueColor]borderColor:[UIColoryellowColor]];

}

//************************ 以前一行代码实现 *************************

+ (instancetype)createLabelWithContent:(NSString*)content addView:(UIView*)view lableX:(CGFloat)lableX lableY:(CGFloat)lableY lableH:(CGFloat)lableH fontSize:(CGFloat)fontSize backgroundColor:(UIColor*)backgroundColor textColor:(UIColor*)textColor borderColor:(UIColor*)borderColor{

NSString*string = [NSStringstringWithFormat:@"%@",content];

CGRecttextRect = [selfboundingString:stringsize:CGSizeMake([UIScreenmainScreen].bounds.size.width, [UIScreenmainScreen].bounds.size.height*2)fontSize:fontSize];

CGFloatrowWidth =0.0;

if(string.length==1) {

rowWidth = textRect.size.width+35;

}else{

rowWidth = textRect.size.width+25;

}

UILabel*lable = [[UILabelalloc]initWithFrame:CGRectMake(lableX, lableY, rowWidth, lableH)];

lable.layer.masksToBounds=YES;

lable.layer.cornerRadius=15;

lable.layer.borderColor= borderColor.CGColor;

lable.layer.borderWidth=1;

lable.backgroundColor= backgroundColor;

lable.textAlignment=NSTextAlignmentCenter;

lable.textColor= textColor;

lable.text= string;

[viewaddSubview:lable];

returnlable;

}

//自动适应lable的宽度和高度

+ (CGRect)boundingString:(NSString*)string size:(CGSize)size fontSize:(NSInteger)fontSize

{

NSStringDrawingOptionsoptions =NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading;

NSDictionary*attributes =@{NSFontAttributeName: [UIFontsystemFontOfSize:fontSize]};

return[stringboundingRectWithSize:sizeoptions:optionsattributes:attributescontext:nil];

}

你可能感兴趣的:(iOS UILable 自适应宽度和高度)