1.根据字体多少使UILabel自动调节尺寸 2.跑马灯

<span style="font-size:14px;"></span>

在大多属性情况下,给UILabel进行动态数据绑定的时候,往往需要根据字符串的多少,动态调整UILabel的宽度或高度。

下面分两种情况考虑:

1、UILabel宽度不变,根据字体多少,自动调整UILabel的高度,并折行显示。

代码如下:

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 200, 20)];
    label.font = [UIFont boldSystemFontOfSize:20.0f];  //UILabel的字体大小
    label.numberOfLines = 0;  //必须定义这个属性,否则UILabel不会换行
    label.textColor = [UIColor whiteColor]; 
    label.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    [label setBackgroundColor:[UIColor redColor]];
    
    //宽度不变,根据字的多少计算label的高度
    NSString *str = @"可以更改此内容进行测试,宽度不变,高度根据内容自动调节";
    CGSize size = [str sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    //根据计算结果重新设置UILabel的尺寸
    [label setFrame:CGRectMake(0, 10, 200, size.height)];
    label.text = str;
    
    [self.view addSubview:label];


2、UILabel高度不变,根据字体多少,自动调整UILabel的宽度,并折行显示

代码如下:

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 20, 20)];
    label.font = [UIFont boldSystemFontOfSize:20.0f];  //UILabel的字体大小
    label.numberOfLines = 0;  //必须定义这个属性,否则UILabel不会换行
    label.textColor = [UIColor whiteColor]; 
    label.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    [label setBackgroundColor:[UIColor redColor]];
    
    //高度固定不折行,根据字的多少计算label的宽度
    NSString *str = @"高度不变获取宽度,获取字符串不折行单行显示时所需要的长度";
    CGSize size = [str sizeWithFont:label.font constrainedToSize:CGSizeMake(MAXFLOAT, label.frame.size.height)];
    NSLog(@"size.width=%f, size.height=%f", size.width, size.height);
    //根据计算结果重新设置UILabel的尺寸
    [label setFrame:CGRectMake(0, 10, size.width, 20)];
    label.text = str;
    
    [self.view addSubview:label];
其中两种情况,核心代码均为size处的代码,均要把对应的size设置为MAXFLOAT
------------------------------------------------------------------
跑马灯
<span style="font-size:24px;">  </span><span style="font-size:14px;">[runLabel sizeToFit];
    CGRect frame = runLabel.frame;
    frame.origin.x = 320;
    runLabel.frame = frame;
    
    [UIView beginAnimations:@"testAnimation" context:NULL];
    [UIView setAnimationDuration:8.8f];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationRepeatAutoreverses:NO];
    [UIView setAnimationRepeatCount:999999];
    
    frame = runLabel.frame;
    frame.origin.x = -frame.size.width;
    runLabel.frame = frame;
    [UIView commitAnimations];</span>




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值