iOS开发笔记--详解UILabel的相关属性设置

2020-01-18 16:59:29刘景俊

根据文本数量自动调整label高度

其实就是用上面的方法得到高度再生成label


NSString *text =[[NSString alloc]init];  
 text = @"输入文本内容";  
 CGSize size = CGSizeMake(280, 180);  
 UIFont *fonts = [UIFont systemFontOfSize:14.0];  
 CGSize msgSie = [text sizeWithFont:fonts constrainedToSize:size lineBreakMode: NSLineBreakByCharWrapping];  
 UILabel *textLabel = [[UILabel alloc] init];  
 [textLabel setFont:[UIFont boldSystemFontOfSize:14]];  
 textLabel.frame = CGRectMake(20,70, 280,msgSie.height);  
 textLabel.text = text;  
 textLabel.lineBreakMode = NSLineBreakByCharWrapping;//实现文字多行显示  
 textLabel.numberOfLines = 0;  
 [self.view addSubview:textLabel];  
 设置label的边框粗细与颜色,设置前要在相应文件中加入#import<QuartzCore/QuartzCore.h>
 label.layer.borderColor = [UIColor lightGrayColor].CGColor;//边框颜色,要为CGColor  
label.layer.borderWidth = 1;//边框宽度  

设置label的背景颜色


label.backgroundColor =[UIColor yellowColor];  

设置label背景图

设置背景图有两种方法,下面先介绍第一种方法:

设置背景图可以把一张大小与label一样的图放在label的后面一层,然后把label的背景设置为透明,这样实现label有背景


UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 200, 400)];  
UIImageView *imageView =[[UIImageView alloc]init];  
imageView.frame =CGRectMake(50, 50, 200, 400);  
UIImage *image=[UIImage imageNamed:@"1.jpg"];  
imageView.image =image;//imageView会根据自身大小改变添加的图片的大小所以不需要额外设置image  
label.backgroundColor = [UIColor clearColor];  
label.text =@"hello world";  
label.font = [UIFont systemFontOfSize:30];  
label.textColor = [UIColor yellowColor];  
[self.view addSubview:imageView];//添加的顺序不能错,否则图片会覆盖label  
[self.view addSubview:label]; 

  这个是一个有点不正统的方法,下面要介绍更加规范的第二种方法:用UIColor设置图片,然后把UIColor作为背景颜色,就可以实现label设置背景图


UIColor * color = [UIColor colorWithPatternImage:image];//image为需要添加的背景图  
 UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 100, 200)];  
 [label setBackgroundColor:color];  
 [self.view addSubview:label];  

但这个方法有一个严重的缺陷,就是当背景图的尺寸与label大小不一致时,会出现背景图被部分截取或者平铺重复的情况,所以更完善的方法是要先修改好背景图的大小与label大小一致再设置背景颜色。可以用下面的函数设置image尺寸


 -(UIImage *)scaleImage:(UIImage *)img ToSize:(CGSize)itemSize{  
  UIImage *i;  
  // 创建一个bitmap的context,并把它设置成为当前正在使用的context  
  UIGraphicsBeginImageContext(itemSize);  
  CGRect imageRect=CGRectMake(0, 0, itemSize.width, itemSize.height);  
  // 绘制改变大小的图片  
  [img drawInRect:imageRect];  
  // 从当前context中创建一个改变大小后的图片  
  i=UIGraphicsGetImageFromCurrentImageContext();  
  // 使当前的context出堆栈  
  UIGraphicsEndImageContext();  
  // 返回新的改变大小后的图片  
  return i;  
}