// 第一個參數:字體大小,字體大小/樣式影響計算字體的高度
// 第二個參數:CGSize結構體,結構體中第一個參數表示寬度,寬度的設置影響計算文本的高度,很明顯越寬,高度越小;結構體中第二個參數表示最大能有多高,好比咱們寫爲100,那麼即便文本高度計算出來是200, 這個方法也會返回100, 因此通常狀況下咱們把它寫爲MAXFLOAT, 表示能有多高返回多高
if ([[[UIDevice currentDevice] systemVersion] floatValue] <= 7.0) {
CGSize size = [str sizeWithFont:self.showLabel.font constrainedToSize:CGSizeMake(self.showLabel.frame.size.width, MAXFLOAT)];
// 計算出文本高度後,從新給label賦值
CGRect frame = self.showLabel.frame;
frame.size.height = size.height;
self.showLabel.frame = frame;
} else {
/*
// 計算text的高度,改變label的高,讓label適應這些文字
CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:18.0] constrainedToSize:CGSizeMake(self.targetLabel.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
// 第一個參數:字體
// 第二個參數:constraintedSize
// 第三個參數:換行模式
*/
// after iOS7: boundingRectWithSize:options:attributes:context:
CGSize textSize = [str boundingRectWithSize:CGSizeMake(self.showLabel.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17.0]} context:nil].size;
// 選項options:
/**
* NSStringDrawingUsesLineFragmentOrigin:
繪製文本時使用 line fragement origin 而不是 baseline origin
NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine
* NSStringDrawingUsesFontLeading:
計算行高時使用行距。(譯者注:字體大小+行間距=行距)
* NSStringDrawingTruncatesLastVisibleLine:
若是文本內容超出指定的矩形限制,文本將被截去並在最後一個字符後加上省略號。
* NSStringDrawingUsesDeviceMetrics:
計算佈局時使用圖元字形(而不是印刷字體)。
*/
CGRect frame = self.showLabel.frame;
frame.size.height = textSize.height;
self.showLabel.frame = frame;
}
self.showLabel.text = @"xxxxxxx";//你的文本內容
【拓】同理能夠設計一個可變高度(根據內容自適應高度)的 UITableViewCell app
1) 建立並添加一個 UILabel 做爲單元格 cell 的子視圖;
2) 在 UITableView 的委託方法: (CGFloat)tableView:(UITableView*)tableViewheightForRowAtIndexPath: (NSIndexPath *) indexPath 中計算高度
3) 在 UITableView 的委託方法: (UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexP ath: (NSIndexPath *) indexPath 中計算 UILabel 的框大小。
佈局