tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
這個(gè)方法用于返回一個(gè) cell 的預(yù)估高度祠饺,如果在程序中實(shí)現(xiàn)了這個(gè)方法,tableview 首次加載的時(shí)候就不會調(diào)用heightForRowAtIndexPath
方法斥废,而是用estimatedHeightForRowAtIndexPath
返回的預(yù)估高度計(jì)算 tableview 的總高度厅贪,然后 tableview 就可以顯示出來了魔慷,等到 cell 可見的時(shí)候,再去調(diào)用heightForRowAtIndexPath
獲取 cell 的正確高度。
通過使用 estimatedHeightForRowAtIndexPath
這個(gè) Delegate 方法记舆,解決了首次加載 table view 出現(xiàn)的性能問題。但還有一個(gè)麻煩的問題呼巴,就是在 cell 沒有被加載的時(shí)候計(jì)算 cell 的高度泽腮,上面給出的代碼中,僅僅是計(jì)算一個(gè) NSString 的高度衣赶,就需要不少代碼了诊赊。這種計(jì)算實(shí)際上是必須的,然而在 iOS 8 開始府瞄,你可能可以不用再寫這些煩人的計(jì)算代碼了碧磅!前提是你要會使用 storyboard。
在 iOS 8 中,self size cell 提供了這樣一種機(jī)制:cell 如果有一個(gè)確定的寬度/高度鲸郊,autolayout 會自動(dòng)根據(jù) cell 中的內(nèi)容計(jì)算出對應(yīng)的高度/寬度敲街。
請看:
*** iOS 8 自適應(yīng) Cell ***
.
2、 cell重用問題
官網(wǎng)是這樣子說的严望。
// 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滾動(dòng)導(dǎo)致數(shù)據(jù)混亂 準(zhǔn)備重用,防止?jié)L動(dòng)出現(xiàn)數(shù)據(jù)錯(cuò)亂 ,你可以在里面設(shè)置值為nil,例如:***
self.timeLineBill = nil;
self.categoryImageBtn.imageView.image = nil;
在使用cell時(shí)作為網(wǎng)絡(luò),還需要在這里通知取消掉前一次網(wǎng)絡(luò)請求.不要再給這個(gè)cell發(fā)數(shù)據(jù)
多艇,下面的方法是可以簡單的根據(jù)identifier 進(jìn)行重用,數(shù)據(jù)復(fù)雜時(shí)就不可以了像吻。
static NSString *CellIdentifier = @"Identifier";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}