iOS UILable 自适应宽度和高度

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

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


#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];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容