ios- UILabel - 相关设置

来源:互联网 发布:天心天思软件 编辑:程序博客网 时间:2024/05/17 07:13


1:根据字体多少使UILabel自动调节尺寸

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

下面分两种情况考虑:

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

代码如下:

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

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

代码如下:

  1. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 20, 20)];  
  2. label.font = [UIFont boldSystemFontOfSize:20.0f];  //UILabel的字体大小  
  3. label.numberOfLines = 0;  //必须定义这个属性,否则UILabel不会换行  
  4. label.textColor = [UIColor whiteColor];   
  5. label.textAlignment = NSTextAlignmentLeft;  //文本对齐方式  
  6. [label setBackgroundColor:[UIColor redColor]];  
  7.   
  8. //高度固定不折行,根据字的多少计算label的宽度  
  9. NSString *str = @"高度不变获取宽度,获取字符串不折行单行显示时所需要的长度";  
  10. CGSize size = [str sizeWithFont:label.font constrainedToSize:
  11.                 CGSizeMake(MAXFLOAT, label.frame.size.height)];  
  12. NSLog(@"size.width=%f, size.height=%f", size.width, size.height);  
  13. //根据计算结果重新设置UILabel的尺寸  
  14. [label setFrame:CGRectMake(0, 10, size.width, 20)];  
  15. label.text = str;  
  16.   
  17. [self.view addSubview:label];  
  18. [label release];  

co其中两种情况,核心代码均为size处的代码,均要把对应的size设置为MAXFLOAT


2:UILabel上加点击事件

     

           //要设置这个属性为yes     

             contentLabel.userInteractionEnabled =YES;

            //label上加一个点击事件

            UITapGestureRecognizer *tapname = [[UITapGestureRecognizeralloc

                                                    initWithTarget:selfaction:@selector(tapEvent:)];

            tapname.numberOfTapsRequired =1 ;

            [contentLabeladdGestureRecognizer:tapname];


  




0 0
原创粉丝点击