ios開發點滴-UILable 根據文字內容進行大小設定 sizeThatFits和sizeToFit
阿新 • • 發佈:2019-02-03
轉自:http://blog.csdn.net/senyangs/article/details/21078611
1.定義一個UILable
- self.view.backgroundColor =[UIColor whiteColor];
- NSString *str=@"目前支援以下站點";
- UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
- //文字文字自適應大小
- notice.adjustsFontSizeToFitWidth = YES;
- notice.text=str;
-
notice.textAlignment
- CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero];
- notice.center = CGPointMake(self.view.bounds.size.width/2, 20) ;
- notice.textColor=[UIColor whiteColor];
- notice.backgroundColor=[UIColor blackColor];
- [self.view addSubview:notice];
得到的效果如下圖
自適應大小ios7以後有兩種可行的方案:
1.sizeThatFits
- NSString *str=@"目前支援以下站點";
- UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
- //文字文字自適應大小
- notice.adjustsFontSizeToFitWidth = YES;
- notice.text=str;
- notice.textAlignment=NSTextAlignmentCenter;
- //使用sizeThatFit計算lable大小
-
CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero];
- //重新指定frame
- notice.frame=CGRectMake(0, 0, sizeThatFit.width, sizeThatFit.height);
- notice.center = CGPointMake(self.view.bounds.size.width/2, kL20) ;
- notice.textColor=[UIColor whiteColor];
- notice.backgroundColor=[UIColor blackColor];
- [self.view addSubview:notice];
效果圖:
2.sizeToFit
- NSString *str=@"目前支援以下站點";
- UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
- //文字文字自適應大小
- notice.adjustsFontSizeToFitWidth = YES;
- notice.text=str;
- notice.textAlignment=NSTextAlignmentCenter;
- [notice sizeToFit];//使用sizeToFit
- notice.center = CGPointMake(self.view.bounds.size.width/2, kL20) ;
- notice.textColor=[UIColor whiteColor];
- notice.backgroundColor=[UIColor blackColor];
- [self.view addSubview:notice];
效果圖:
注意:1.計算lable大小的時候需要先進行lable的text賦值
2.如果要將lable居中顯示的話,lable.center屬性的設定必須放在設定新大小之後,不然會出現不居中的情況
3.ios7之前還有其他的方法
cgSize=[str sizeWithFont:font];
這個方法是NSString的方法,聽說在ios7下使用會計算不準確