iOS UILabel UITextView自適應文本,或文本大小自適應

 
 
//UILabel自適應文本的高度

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 300, 100)];

    label.numberOfLines = 0;

    label.lineBreakMode = NSLineBreakByWordWrapping;

    label.text = @"是它嗎?哈哈,太興奮了。」12日,隨着土豪金版100元人民幣正式發行,到了中午,很多長春市民也陸續在其朋友圈曬出了他們拿到的新版人民幣。不過,先別高興,很多驗鈔機還沒升級,可能誤認它是假鈔。";

    CGSize size = [label sizeThatFits:CGSizeMake(label.frame.size.width, MAXFLOAT)];

    label.frame =CGRectMake(0, 100, 300, size.height);

    label.font = [UIFont systemFontOfSize:14];

    [self.view addSubview:label];

 

如下方法能夠作到在固定label大小裏面根據文本多少來肯定字體的大小。app

//讓文本自適應Label

    //常常遇到,UILabel裏面的顯示區域固定,   可是裏面的文字顯示合適的字體大小的時候,能夠用下面的方法:

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(200, 350, 200, 30)];

    label.backgroundColor = [UIColor clearColor];

    label.textColor = [UIColor redColor];

    label.font = [UIFont systemFontOfSize:20];

    label.adjustsFontSizeToFitWidth = YES;

    label.minimumFontSize = 6;//默認爲0

    label.text = @"flying in the sky";

    //就是在空間夠的狀況下,使用20號字體,若是空間不夠,那麼就會自動將字體向下調整,可是也不會少於6號字體,若是6號字體也顯示不完,後續顯示省略號。。。

    [self.view addSubview:label];

另一些自適應文本高度的方法:字體

//自適應label高度,方法一:
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 225, 300, 180)]; NSString *text = @"First take clear picture and then try to zoom in to fit the "; label.text = text; label.lineBreakMode = UILineBreakModeWordWrap; //這個是關鍵 label.numberOfLines = 0; //這個是關鍵  CGSize maximumSize = CGSizeMake(300, CGFLOAT_MAX); // 第一個參數是label的寬度,第二個參數是固定的宏定義,CGFLOAT_MAX CGSize expectedLabelSize = [text sizeWithFont:label.font constrainedToSize:maximumSize lineBreakMode:UILineBreakModeWordWrap]; CGRect newFrame = label.frame; newFrame.size.height = expectedLabelSize.height; label.frame = newFrame; [label sizeToFit]; [self addSubview:label];

綜合主要代碼:spa

UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 225, 300, 180)];
NSString *string = @"First take clear picture and then try to zoom in to fit the "; 
CGRect orgRect=self.label.frame;//獲取原始UILabel的frame  
[label  setNumberOfLines:0];   //numberoflines爲0,即不作行數的限制  
CGSize size = [string sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(240, 2000)lineBreakMode:UILineBreakModeWordWrap]; 
orgRect.size.height
=size.height+10;  //獲取自適應文本內容高度
[label setFrame: orgRect];   
//重設UILabel的frame
[label setText: string];

UITextView的設置與Label差很少code

NSString *string="是它嗎?哈哈,太興奮了。」12日,隨着土豪金版100元人民幣正式發行,到了中午,很多長春市民也陸續在其朋友圈曬出了他們拿到的新版人民幣。不過,先別高興,很多驗鈔機還沒升級,可能誤認它是假鈔。";//獲取文本內容  
  
CGRect orgRect=self.txtView.frame;//獲取原始UITextView的frame  
  
CGSize  size = [string sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(240, 2000) lineBreakMode:UILineBreakModeWordWrap];    
  
orgRect.size.height=size.height+10;//獲取自適應文本內容高度  
  
    self.txtView.frame=orgRect;//重設UITextView的frame  
  
self.txtView.text=string;  
相關文章
相關標籤/搜索