標籤:ios nsstring uitabelview uitabelviewcell
1.首先,設定 cell 中顯示文本的容器(這裡假設是 Label)的一些屬性,如下:
[_LabelsetNumberOfLines:0];//這個是設定 label 內文本的行數,0 代表自適應
[_LabelsetLineBreakMode:NSLineBreakByWordWrapping];//斷行模式
[_LabelsetFont:[UIFontsystemFontOfSize:16.0]];//字型大小
2.在 Cell 的 - (void)layoutSubviews 方法中,重新設定 cell 中 Label 的高度(根據自適應換行後計算高度)
NSString * text = [_array objectAtIndex:indexPath.row];
cell.Label.text = text;//從資料來源中獲得相對應的資料
NSDictionary * dic = [NSDictionarydictionaryWithObject:[UIFontsystemFontOfSize:16.0]forKey:NSFontAttributeName];//這裡的字型大小要跟你設定的 Label 字型大小一樣
CGSize textSize = [textsizeWithAttributes:dic];//根據字典中的資料計算出 size
CGRect rect = _Label.frame;
rect.size.height = textSize.height;
_Label.frame = rect;
3.最後,修改 Cell 的行高,在設定 Cell 行高的協議方法中再計算一次
NSString * text = [_array objectAtIndex:indexPath.row];
cell.Label.text = text;//從資料來源中獲得相對應的資料
NSDictionary * dic = [NSDictionarydictionaryWithObject:[UIFontsystemFontOfSize:16.0]forKey:NSFontAttributeName];//這裡的字型大小要跟你設定的 Label 字型大小一樣
CGSize textSize = [textsizeWithAttributes:dic];//根據字典中的資料計算出 size
return textSize.height;