欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UILabel的高度和宽度自适应

程序员文章站 2022-05-23 23:14:13
...

今天记录下 UILabel的高度和宽度自适应,方法特别简单

1 创建category

.h中
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font;

+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font;
.m中
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font
{
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    label.text = title;
    label.font = font;
    label.numberOfLines = 0;
    [label sizeToFit];
    CGFloat height = label.frame.size.height;
    return height;
}

+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];
    label.text = title;
    label.font = font;
    [label sizeToFit];
    return label.frame.size.width;
}

2 使用时 引入头文件

#import "UILabel+LabelHeightAndWidth.h"

#pragma mark - labelOne  SizeToFitHeight
- (void)buildLabelOne
{
    UILabel *labelOne = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 200, 50)];
    labelOne.text = @"这是labelOne的高度自适应这是labelOne的高度自适应这是labelOne的高度自适应这是labelOne的高度自适应";
    labelOne.backgroundColor = [UIColor grayColor];
    labelOne.font = [UIFont systemFontOfSize:20];
    labelOne.numberOfLines = 0;
    CGFloat height = [UILabel getHeightByWidth:labelOne.frame.size.width title:labelOne.text font:labelOne.font];
    labelOne.frame = CGRectMake(10, 30, 200, height);
    [self.view addSubview:labelOne];
    
}

#pragma mark - labelTwo  SizeToFitWidth
- (void)buildLabelTwo
{
    UILabel *labelTwo = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 50, 100)];
    labelTwo.text = @"这是labelTwo的宽度自适应这是labelTwo的宽度自适应这是labelTwo的宽度自适应";
    labelTwo.backgroundColor = [UIColor cyanColor];
    labelTwo.font = [UIFont systemFontOfSize:20];
    CGFloat width = [UILabel getWidthWithTitle:labelTwo.text font:labelTwo.font];
    labelTwo.frame = CGRectMake(10, 300, width, 100);
    [self.view addSubview:labelTwo];
}

效果如下图


UILabel的高度和宽度自适应
EEC19BD7-5C46-4284-B66D-7F31CEB87E4D.png