1. 程式人生 > >ios開發點滴-UILable 根據文字內容進行大小設定 sizeThatFits和sizeToFit

ios開發點滴-UILable 根據文字內容進行大小設定 sizeThatFits和sizeToFit

轉自:http://blog.csdn.net/senyangs/article/details/21078611

1.定義一個UILable 

  1. self.view.backgroundColor =[UIColor whiteColor];  
  2. NSString *str=@"目前支援以下站點";  
  3. UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0020020)];  
  4. //文字文字自適應大小
  5. notice.adjustsFontSizeToFitWidth = YES;  
  6. notice.text=str;  
  7. notice.textAlignment
    =NSTextAlignmentCenter;  
  8. CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero];  
  9.  notice.center = CGPointMake(self.view.bounds.size.width/220) ;  
  10. notice.textColor=[UIColor whiteColor];  
  11. notice.backgroundColor=[UIColor blackColor];  
  12. [self.view addSubview:notice];  

得到的效果如下圖

自適應大小ios7以後有兩種可行的方案:

1.sizeThatFits

  1. NSString *str=@"目前支援以下站點";  
  2.  UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0020020)];  
  3.  //文字文字自適應大小
  4.  notice.adjustsFontSizeToFitWidth = YES;  
  5.  notice.text=str;  
  6.  notice.textAlignment=NSTextAlignmentCenter;  
  7.  //使用sizeThatFit計算lable大小
  8.  CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero];  
  9.  //重新指定frame
  10.  notice.frame=CGRectMake(00, sizeThatFit.width, sizeThatFit.height);  
  11.  notice.center = CGPointMake(self.view.bounds.size.width/2, kL20) ;  
  12.  notice.textColor=[UIColor whiteColor];  
  13.  notice.backgroundColor=[UIColor blackColor];  
  14.  [self.view addSubview:notice];  

效果圖:

2.sizeToFit

  1. NSString *str=@"目前支援以下站點";  
  2. UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0020020)];  
  3. //文字文字自適應大小
  4. notice.adjustsFontSizeToFitWidth = YES;  
  5. notice.text=str;  
  6. notice.textAlignment=NSTextAlignmentCenter;  
  7. [notice sizeToFit];//使用sizeToFit
  8. notice.center = CGPointMake(self.view.bounds.size.width/2, kL20) ;  
  9. notice.textColor=[UIColor whiteColor];  
  10. notice.backgroundColor=[UIColor blackColor];  
  11. [self.view addSubview:notice];  


效果圖:

注意:1.計算lable大小的時候需要先進行lable的text賦值

    2.如果要將lable居中顯示的話,lable.center屬性的設定必須放在設定新大小之後,不然會出現不居中的情況

    3.ios7之前還有其他的方法

cgSize=[str sizeWithFont:font];

這個方法是NSString的方法,聽說在ios7下使用會計算不準確