卡頓原因:cell賦值內(nèi)容時(shí),會(huì)根據(jù)內(nèi)容設(shè)置布局,也就可以知道cell的高度哲嘲,若有1000行,就會(huì)調(diào)用1000次 cellForRow方法媳禁,而我們對(duì)cell的處理操作眠副,都是在這個(gè)方法中賦值,布局等等竣稽,開銷很大囱怕。
1.提前計(jì)算并緩存好高度(布局),因?yàn)閔eightForRowAtIndexPath:是調(diào)用最頻繁的方法
在獲得數(shù)據(jù)后毫别,直接先根據(jù)數(shù)據(jù)源計(jì)算出對(duì)應(yīng)的布局娃弓,并緩存到數(shù)據(jù)源中,這樣在tableView:heightForRowAtIndexPath:方法中就直接返回高度岛宦,而不需要每次都計(jì)算了
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = self.dataList[indexPath.row];
CGRect rect = [dict[@"frame"] CGRectValue];
return rect.frame.height;
}
2.==賦值和計(jì)算布局分離==台丛。cellForRow負(fù)責(zé)賦值,heightRorRow負(fù)責(zé)計(jì)算高度砾肺。
3.自定義cell繪制異步繪制
給自定義的Cell添加draw方法
采用異步繪制挽霉,如果在重寫drawRect方法就不需要用GCD異步線程了,因?yàn)閐rawRect本來(lái)就是異步繪制的债沮。
4.滑動(dòng)UITableView時(shí)炼吴,按需加載對(duì)應(yīng)的內(nèi)容(大量圖片展示,網(wǎng)絡(luò)加載的時(shí)候很管用)
//按需加載 - 如果目標(biāo)行與當(dāng)前行相差超過(guò)指定行數(shù)疫衩,只在目標(biāo)滾動(dòng)范圍的前后指定3行加載硅蹦。
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
NSIndexPath *ip = [self indexPathForRowAtPoint:CGPointMake(0, targetContentOffset->y)];
NSIndexPath *cip = [[self indexPathsForVisibleRows] firstObject];
NSInteger skipCount = 8;
if (labs(cip.row-ip.row)>skipCount) {
NSArray *temp = [self indexPathsForRowsInRect:CGRectMake(0, targetContentOffset->y, self.width, self.height)];
NSMutableArray *arr = [NSMutableArray arrayWithArray:temp];
if (velocity.y<0) {
NSIndexPath *indexPath = [temp lastObject];
if (indexPath.row+33) {
[arr addObject:[NSIndexPath indexPathForRow:indexPath.row-3 inSection:0]];
[arr addObject:[NSIndexPath indexPathForRow:indexPath.row-2 inSection:0]];
[arr addObject:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0]];
}
}
[needLoadArr addObjectsFromArray:arr];
}
}
//在tableView:cellForRowAtIndexPath:方法中加入判斷:
if (needLoadArr.count>0&&[needLoadArr indexOfObject:indexPath]==NSNotFound) {
[cell clear];
return;
}
滾動(dòng)很快時(shí),只加載目標(biāo)范圍內(nèi)的Cell闷煤,這樣按需加載童芹,極大的提高流暢度。