Objective-C学习-UILabel的使用

label.adjustsFontSizeToFitWidth = YES;  让字体自适应label

label.numberOfLines = [label.text length];  竖向显示文本

 

UILabel 高度根据内容多少来改变

1.新建类别
UILabel+BoundingRect.h 

#import

 

@interface UILabel (BoundingRect)

 

//初始化的size,size中高度或者宽度为0

-(CGRect)boundingRectWithInitSize:(CGSize)size;

 

@end

 

UILabel+BoundingRect.m

#import "UILabel+BoundingRect.h"

 

@implementation UILabel (BoundingRect)

 

-(CGRect)boundingRectWithInitSize:(CGSize)size

{

  

    self.lineBreakMode=NSLineBreakByWordWrapping;

    

    CGRect rect=[self.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:self.font,NSFontAttributeName, nil] context:nil];

    

    return rect;

}

 

 

@end

 

 //给定宽度,要知道label的高度

    self.label=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 0)];

    self.label.font=[UIFont fontWithName:@"HelveticaNeue" size:18.0f];

    self.label.text=@"潇洒哥:最近怎样?在那里呆的还习惯吗?哪天聚一聚,一起吃顿饭";

    self.label.textColor=[UIColor darkGrayColor];

    [self.view addSubview:self.label];

    

    self.label.numberOfLines=0; //PS:这句很主要,否则默认行数为1,只显示一行文字后面截断了就没有了

    CGRect myRect=[self.label boundingRectWithInitSize:self.label.frame.size];

    self.label.frame=CGRectMake(100, 100, 200, myRect.size.height+100);

 

 

反之,也可以固定高度,来确定label的宽度。

 
boundingRect求出的高度总是为0,
原因没有设置好text font (或者没有固定宽度)
text font 一定要在boundingRect方法前设置好
 

 

在UILabel显示不同的字体和颜色

UILabel *matchScoreLabel = [[UILabel alloc] initWithFrame:...];

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];

    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,4)];

    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];

    [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];

    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)];

    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0] range:NSMakeRange(6, 12)];

    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(19, 6)];

matchScoreLabel.attributedText = str;

转载于:https://www.cnblogs.com/xvewuzhijing/p/4901542.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值