歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> (iPhone/iPad開發)根據文本的字數自動調整UILabel的寬高

(iPhone/iPad開發)根據文本的字數自動調整UILabel的寬高

日期:2017/3/1 10:36:11   编辑:Linux編程
NSString * myText = [NSString stringWithString:@"some text"];
//獲取到文本大大小
CGFloat constrainedSize = 265.0f; //其他大小也行
UIFont * myFont = [UIFont fontWithName:@"Arial" size:19]; // UILabel使用的字體
CGSize textSize = [myText sizeWithFont: myFont
constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX)

lineBreakMode:UILineBreakModeWordWrap];


textSize.width

textSize.height

即為UILable的寬和高,

CGRect labelFrame = CGRectMake (0, 0, textSize.width, textSize.height);
UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];

即可用到

工整一些做法:

[cpp]

  1. //計算文本所占高度
  2. //2個參數:寬度和文本內容
  3. -(CGFloat)calculateTextHeight:(CGFloat)widthInput Content:(NSString *)strContent{
  4. CGSize constraint = CGSizeMake(widthInput, 20000.0f);
  5. CGSize size = [strContent sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
  6. CGFloat height = MAX(size.height, 44.0f);
  7. return height;
  8. }
  9. //計算 寬度
  10. -(CGFloat)calculateTextWidth:(NSString *)strContent{
  11. // CGSize constraint = CGSizeMake(heightInput, heightInput);
  12. CGFloat constrainedSize = 26500.0f; //其他大小也行
  13. CGSize size = [strContent sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
  14. // CGFloat height = MAX(size.height, 44.0f);
  15. return size.width;
  16. }
Copyright © Linux教程網 All Rights Reserved