使用aulayout自適應uitableviewcell高度

在使用autolayout的項目中,單元格的自適應高度,可能有點複雜,特別是對於複雜一點的自定義單元格;那麼下面就這個autolayout自適應單元格,經過代碼來講明:佈局


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {字體

    SGSuggestionRootTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];網站

    cell.frame = CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 0);spa

    //標記須要從新佈局從新佈局資源

    [cell.contentView setNeedsLayout];字符串

    //使佈局當即生效it

    [cell.contentView layoutIfNeeded];io

//    id obj = [[NSArray alloc] objectAtIndex:indexPath.row]table

    CGRect questionRect = [@"大家網站有人亂髮垃圾信息" boundingRectWithSize:CGSizeMake(cell.questionLabel.frame.size.widthobject

                                                                                          , CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.]} context:nil];

    CGRect sugContentRect = [@"大家網站有人亂髮垃圾信息,好多廣告,但願趕忙清除!" boundingRectWithSize:CGSizeMake(cell.sugContentLabel.frame.size.width

                                                                                        , CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.]} context:nil];

    CGRect fbContentRect = [@"大家網站有人亂髮垃圾信息,好多廣告,但願趕忙清除!發順豐撒啊事發地點薩芬撒發順豐的法師法師嘎斯發噶沙發沙發上防輻射的方式和發上防輻射的方式和發上防輻射的方式和" boundingRectWithSize:CGSizeMake(cell.fbContentLabel.frame.size.width

                                                                                        , CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.]} context:nil];

    //15是固定的控件間的間隙

    CGFloat sum = questionRect.size.height + sugContentRect.size.height + fbContentRect.size.height + 15;

    return sum;

}


以上代碼是獲取計算單元格的高度,紅色字體部分是須要注意的,由於是經過重用機制獲取的cell的frame寬度有問題,因此從新設置合適的寬度,而後經過     [cell.contentView setNeedsLayout]; 標記爲待從新佈局,  經過    [cell.contentView layoutIfNeeded]; 當即調用 layoutsubview方法,從而獲取questionLabel、sugContentLabel、fbContentLabel這三個控件根據約束條件生成的width,(爲節省資源,可將紅色代碼放到viewdidload中) 而後經過boundingRectWithSize這個方法和width計算出顯示字符串的bound, 獲得這些bound後,根據實際狀況進行運算獲取,將要顯示單元格的高度


 (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 中設置label的高度,在下面的代碼中使用的是masonry這個對手寫autolayout進行封裝的開源類庫,代碼如:

    [label mas_updateConstraints:^(MASConstraintMaker *make) {

        make.height.greaterThanOrEqualTo(@(rect.size.height));

    }];

須要注意的是,因爲使用了autolayout,多行label高度須要設置爲大於等於,而不能設置爲等於

相關文章
相關標籤/搜索