tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
這個方法用于返回一個 cell 的預估高度,如果在程序中實現(xiàn)了這個方法,tableview 首次加載的時候就不會調用heightForRowAtIndexPath
方法,而是用estimatedHeightForRowAtIndexPath
返回的預估高度計算 tableview 的總高度,然后 tableview 就可以顯示出來了,等到 cell 可見的時候,再去調用heightForRowAtIndexPath
獲取 cell 的正確高度。
通過使用 estimatedHeightForRowAtIndexPath
這個 Delegate 方法,解決了首次加載 table view 出現(xiàn)的性能問題。但還有一個麻煩的問題,就是在 cell 沒有被加載的時候計算 cell 的高度,上面給出的代碼中,僅僅是計算一個 NSString 的高度,就需要不少代碼了。這種計算實際上是必須的,然而在 iOS 8 開始,你可能可以不用再寫這些煩人的計算代碼了!前提是你要會使用 storyboard。
在 iOS 8 中,self size cell 提供了這樣一種機制:cell 如果有一個確定的寬度/高度,autolayout 會自動根據(jù) cell 中的內容計算出對應的高度/寬度。
請看:
*** iOS 8 自適應 Cell ***
.
2、 cell重用問題
官網是這樣子說的。
// if the cell is reusable (has a reuse identifier), this is called just before the cell is returned from the table view method dequeueReusableCellWithIdentifier:. If you override, you MUST call super.
- (void)prepareForReuse{
[super prepareForReuse];
}
*** 解決tableView滾動導致數(shù)據(jù)混亂 準備重用,防止?jié)L動出現(xiàn)數(shù)據(jù)錯亂 ,你可以在里面設置值為nil,例如:***
self.timeLineBill = nil;
self.categoryImageBtn.imageView.image = nil;
在使用cell時作為網絡,還需要在這里通知取消掉前一次網絡請求.不要再給這個cell發(fā)數(shù)據(jù)
,下面的方法是可以簡單的根據(jù)identifier 進行重用,數(shù)據(jù)復雜時就不可以了。
static NSString *CellIdentifier = @"Identifier";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}