-(void)initUserInterface { UILabel *label = [[UILabel alloc]init]; label.numberOfLines = 0; // 須要把顯示行數設置成無限制 label.font = [UIFont systemFontOfSize:15]; label.textAlignment = NSTextAlignmentCenter; label.text = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; CGSize size = [self sizeWithString:label.text font:label.font]; label.bounds = CGRectMake(0, 0, size.width, size.height); label.center = self.view.center; [self.view addSubview:label]; }
// 定義成方法方便多個label調用 增長代碼的複用性字體
-(CGSize)sizeWithString:(NSString *)string font:(UIFont *)font { CGRect rect = [string boundingRectWithSize:CGSizeMake(320, 8000)//限制最大的寬度和高度 options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin//採用換行模式 attributes:@{NSFontAttributeName: font}//傳人的字體字典 context:nil]; return rect.size; }
方法二:spa
CGRect contentRect = [NSString heightForString:badgeValue Size:contentSize Font:kValueFont]; //獲取某固定文本的顯示高度 +(CGRect)heightForString:(NSString*)str Size:(CGSize)size Font:(UIFont*)font { return [NSString heightForString:str Size:size Font:font Lines:0]; } +(CGRect)heightForString:(NSString*)str Size:(CGSize)size Font:(UIFont*)font Lines:(NSInteger)lines { if (StringIsNullOrEmpty(str)) { return CGRectMake(0, 0, 0, 0); } static UILabel *lbtext; if (lbtext==nil) { lbtext = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)]; }else{ lbtext.frame=CGRectMake(0, 0, size.width, size.height); } lbtext.font=font; lbtext.text=str; lbtext.numberOfLines=lines; CGRect rect= [lbtext textRectForBounds:lbtext.frame limitedToNumberOfLines:lines]; if(rect.size.height<0) rect.size.height=0; if (rect.size.width<0) { rect.size.width=0; } return rect; }
/**code
@return 根據字符串的的長度來計算UITextView的高度
*/orm
+(float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{blog
float height = [[NSString stringWithFormat:@"%@\n",value] boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil].size.height; return height;
}圖片
/**字符串
UITextView根據內容自動改變frame
*/string
(void)textViewDidChange:(UITextView *)textView
{flash
[textView flashScrollIndicators]; // 閃動滾動條 static CGFloat maxHeight = 130.0f; CGRect frame = textView.frame; CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT); CGSize size = [textView sizeThatFits:constraintSize]; if (size.height >= maxHeight) { size.height = maxHeight; textView.scrollEnabled = YES; // 容許滾動 } else { textView.scrollEnabled = NO; // 不容許滾動,當textview的大小足以容納它的text的時候,須要設置scrollEnabed爲NO,不然會出現光標亂滾動的狀況 } textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
}it