一、cell自適應高度
self.tableView.estimatedRowHeight = 60;//預設高度
//或者:estimatedHeightForRowAtIndexPath代理方法中設置
self.tableView.rowHeight = UITableViewAutomaticDimension;
設置的AutoLayout 約束必須讓 cell 的 contentView知道如何自動伸展。關鍵點是 contentView 的 4 個邊都要設置連接到內容的約束,并且內容是會動態改變尺寸的。其實只要記住,我們在設置約束時只要能讓contentView能被內容撐起來就可以了。
參考http://www.lxweimin.com/p/bbe8094e147d
緩存cell的高度,代碼如下:
@property (nonatomic, strong) NSMutableDictionary *heightAtIndexPath;//緩存高度所用字典
#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber *height = [self.heightAtIndexPath objectForKey:indexPath];
if(height)
{
return height.floatValue;
}else
{
return 100;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber *height = @(cell.frame.size.height);
[self.heightAtIndexPath setObject:height forKey:indexPath];
}
就是用一個字典做容器,在cell將要顯示的時候在字典中保存這行cell的高度。然后在調用estimatedHeightForRowAtIndexPath方法時,先去字典查看有沒有緩存高度,有就返回,沒有就返回一個大概高度。這段代碼其實可以寫在viewController的基類里面,這樣寫一遍就可以每個地方都能緩存cell的高度了
(選自http://www.lxweimin.com/p/64f0e1557562)
這篇文章的demo的Github地址:UITableViewCellHeightDemo
二、優化--------(待增加、修改)
//下面的2段代碼可以加上 可以有效提高流暢度
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
1使用不透明視圖。
極大地提高渲染的速度,如非必要,可以將table cell及其子視圖的opaque屬性設為YES(默認值)。其中的特例包括背景色,它的alpha值應該為1(例如不要使用clearColor);圖像的alpha值也應該為1,或者在畫圖時設為不透明。
2、復用cell
3、不要阻塞主線程。最常見的就是網絡請求、更新數據時,整個界面卡住不動,這種現象的原因就是主線程執行了耗時很長的函數或方法,在其執行完畢前,無法繪制屏幕和響應用戶請求,解決辦法就是使用多線程,讓子線程去執行這些函數或方法。(待了解、、、)
4、自動載入更新數據對用戶來說也很友好,這減少了用戶等待下載的時間,例如每次載入50條信息,那就可以在滾動到倒數第10條以內時,加載更多信息:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (count - indexPath.row < 10 && !updating) {
updating = YES;[self update];}
}
// update方法獲取到結果后,設置updating為[NO]