iOS 自动适应 UILabel 的宽度~demo

来源:互联网 发布:ov7670能接51单片机吗 编辑:程序博客网 时间:2024/05/15 23:56

  //需要分类: 联系人:石虎  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];

}

阅读全文
1 0
原创粉丝点击