天天看點

ios開發筆記之如何讓tableView根據文本内容動态改變cell的高度

  可以根據tableViewCell的width以及文本内容的長度來計算出将這個文本全部顯示出來所需要的height,代碼如下:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = _existedArray[indexPath.row];
    return [self textHeightWithLimitedWidth:cellWidth text:str];
}


- (CGFloat)textHeightWithLimitedWidth:(CGFloat)width text:(NSString *)text {
    NSString *textStr = text;
    if ([NSString isEmpty:textStr]) {
        textStr = @" ";
    }
    //若文本為空字元串,則将其轉化成一個空格,再計算高度

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, width)];
    [label setFont:[UIFont fontWithName:@"HiraKakuProN-W3" size:18]];
    //設定需要的字型以及大小
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:textStr];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 9;
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [textStr length])];
    label.attributedText = attStr;
    //用過NSAttributedString設定行間距
    label.numberOfLines = 0;
    //設定自動換行
    CGSize size = [label sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    //根據寬度、字型大小、行間距等資訊計算高度
    return size.height+27;
    //計算出的height沒有留出文字上下的空白距離,這個27可以根據需要改變
 }
           

繼續閱讀