iOS lable宽度自适应

适用于适配时由于屏幕带小不同lable中的字显示省略号

#import 

@interface AutoWidthLable : UILabel

+ (AutoWidthLable *)lableWithFrame:(CGRect)frame title:(NSString *)title font:(CGFloat)font;

@end
#import "AutoWidthLable.h"

@implementation AutoWidthLable

+ (AutoWidthLable *)lableWithFrame:(CGRect)frame title:(NSString *)title font:(CGFloat)font{
    
    return [[AutoWidthLable alloc] initWithFrame:(CGRect)frame title:(NSString *)title font:(CGFloat)font];
}


- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title font:(CGFloat)font {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.font = [UIFont systemFontOfSize:font];
        self.text = title;
        
        CGSize size = [title sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:font]}];
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, size.width, size.height);
        
    }
    return self;
}


@end

使用

AutoWidthLable *lable = [AutoWidthLable lableWithFrame:CGRectMake(20, 20, 0, 0) title:@"**** **** **** ***** ****" font:18];
lable.backgroundColor = [UIColor redColor];
[self.view addSubview:lable];

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