計算tableview的高度


1、自定義一個Cell,拖一個label。設置cell的上下邊與Cell.contentView間距0,其他約束隨意。這樣,lable對Cell的高度有了一個強約束。設置label的行數為0,高度不設。

2、感謝網友提醒,這里如果是iOS7,還是需要設置Cell的高度,不過可以非常簡化,具體做法如下:

a、在ViewController中創建一個Cell的屬性或成員變量,專門用於計算Cell高度。(做這一步是為了性能優化)比如self.tempCell

b、改寫計算高度的回調

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    id entity = self.dataSourceArray[indexPath.row];

    if (self.tempCell == nil) {

        self.tempCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    }

    self.tempCell.bounds = CGRectMake(0,

                                      0,

                                      CGRectGetWidth(self.tableView.bounds),

                                      CGRectGetHeight(self.tempCell.bounds)

                                      );

    [self.tempCell resetCellWithEntity:entity];

         

    CGFloat height = [self.tempCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    return height > 44 ? height : 44;

}

self.tempCell.bounds = xxxxxx

寫這行是因為tempCell創建出來后,默認寬度不一定符合實際情況。

c、在tempCell的resetCellWithEntity:方法中,加入類似這樣的代碼:

?

1

self.testLable.preferredMaxLayoutWidth = self.frame.size.width;

這是因為UILable根據preferredMaxLayoutWidth的值計算高度。默認不設置,表示由系統自動計算。但自動計算僅在iOS8以后有效。iOS7的話,還是需要手動設置的。

 

3、設置一個數據源,一個NSString的數組,放入長短不同的String進行測試,可以發現顯示正常。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM