iOS -- UILabel的高度自适应

     UILabel是iOS开发经常用到的一个控件,主要用于显示文字。下面记录一些常用的UIlabel的使用。

  先定义:UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];

    1.通过调整字体大小,自适应label的宽度

   label.adjustsFontSizeToFitWidth = YES;  

   2.改变Label中选中字段的颜色

   (0)先定义Label: 

        UILabel* noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 200, 100)];

   (1)首先确定要改变颜色字段的位置:

      NSRange colorRange = NSMakeRange(第一个字的位置, 字段长度);

     (2)使用 NSMutableAttributedString(带属性的字符串)。

        初始化方法:

      NSMutableAttributedString *noteStr = [[NSMutableAttributedStringalloc]initWithString:@"今天天气不错呀"];

      添加字符串属性:

        [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:colorRange];

       (3)将带属性字符串设置到label

      [noteLabel setAttributedText:noteStr] ;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel* noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 200, 100)];
    [self changeLabelColor:noteLabel withAllString:@"我是大明星的帅哥" withAimString:@"大明星"];
    [self.view addSubview:noteLabel];
}

//调用该方法就能实现选中字段颜色改变
-(void)changeLabelColor:(UILabel*)noteLabel withAllString:(NSString*)allStr withAimString:(NSString*)aimStr { if (aimStr.length > allStr.length || ![allStr containsString:aimStr]) { return; } noteLabel.textColor = [UIColor darkGrayColor]; NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:allStr]; NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:aimStr].location, aimStr.length); [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.11 green:0.58 blue:0.81 alpha:1] range:redRange]; [noteLabel setAttributedText:noteStr] ; [noteLabel sizeToFit]; }

3. label的 高度自适应

   (1)通过label的   - (CGSize)sizeThatFits:(CGSize)size;  方法拿到 size,重设frame

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 100)];
    label.numberOfLines = 0;
    label.backgroundColor = [UIColor redColor]  ;
    
    label.lineBreakMode = NSLineBreakByWordWrapping;

    label.font = [UIFont systemFontOfSize:18];

    label.text = @"本店于十一期间特推出一系列优惠,限时限量敬请选购!沙发:钻石品质,首领风范!床垫:华贵典雅,彰显时尚!尊贵而不失奢华,典雅却不失自然!温馨和浪漫的生活,我们与你一同创造!";
    
    CGSize size = [label sizeThatFits:CGSizeMake(label.frame.size.width, MAXFLOAT)];
    
    label.frame =CGRectMake(10, 100, 300, size.height);
    
    [self.view addSubview:label];

  (2)通过自动换行,让系统自动设置label高度

    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 100)];
        // 设置文本内容
        label1.text = @"本店于十一期间特推出一系列优惠,限时限量敬请选购!沙发:钻石品质,首领风范!床垫:华贵典雅,彰显时尚!尊贵而不失奢华,典雅却不失自然!温馨和浪漫的生活,我们与你一同创造!";
        label1.font = [UIFont systemFontOfSize:18];

        // 0代表不限制行数
        [label1 setNumberOfLines:0];
        // 因为行数不限制,所以这里在宽度不变的基础上(实际宽度会略为缩小),高度会自动扩充
        [label1 sizeToFit];
        label1.backgroundColor = [UIColor redColor]  ;
        [self.view addSubview:label1];

             

原文地址:https://www.cnblogs.com/huadeng/p/6928527.html