iOS 自动适应 UILabel 的宽度~demo

  //需要分类: 联系人:石虎  QQ: 1224614774 昵称:嗡嘛呢叭咪哄

  //自适应宽度效果:

自动适应 <wbr>UILabel <wbr>的宽度

#import "UILabel+Extension.h"


- (void)viewDidLoad {

    [super viewDidLoad];

     //直接引用分类功能

    [UILabel createLabelWithContent:@"10011111111110" addView:self.view lableX:10lableY:111 lableH:30 fontSize:16 backgroundColor:[UIColor redColor] textColor:[UIColor blueColor] borderColor:[UIColor yellowColor]];    

 

}

 

+ (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 = [NSString stringWithFormat:@"%@",content];

    CGRect textRect = [self boundingString:string size:CGSizeMake([UIScreenmainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height *2)fontSize:fontSize];

    

    CGFloat rowWidth = 0.0;

    if (string.length == 1) {

        rowWidth = textRect.size.width + 35;

    }else{

        rowWidth = textRect.size.width + 25;

    }

    UILabel *lable = [[UILabel alloc]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;

    [view addSubview:lable];    

    return lable;

}

 

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

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

{

    NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;

    

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

    return [string boundingRectWithSize:size options:optionsattributes:attributes context:nil];

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值