iOS TableView性能優化

1. 對象創建;

1.1 TableView初始化

#pragma 懶加載
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - self.cycleScrollView2.frame.size.height)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

1.2 復用cell

從 iOS 6 以后,我們在 UITableView 和 UICollectionView 中可以復用 Cell以及各個 Section 的 Header 和 Footer。

確保TableviewCell/Header/Footer使用了復用機制, 而不是每一次都創建;

@interface HomeVC ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@end

static NSString *cellId = @"Cell";

@implementation HomeVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
//第一種注冊cell<nib文件類HomeTableViewCell>
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil] forCellReuseIdentifier:cellId];

//第二種注冊Cell<純手工打造的HomeVC>
// [self.tableView registerClass:[HomeVC class]forCellReuseIdentifier:cellId];

}

#pragma 代理

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //獲取重用池中的cell
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    //如果沒有取到,就初始化
    if (!cell) {
        cell = [[HomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }

    cell.cellNameLab.text = @"Name";
    return cell;
}

1.2.1 以下為重用相關API
// 復用 Cell:
- [UITableView dequeueReusableCellWithIdentifier:];
- [UITableView registerNib:forCellReuseIdentifier:];
- [UITableView registerClass:forCellReuseIdentifier:];
- [UITableView dequeueReusableCellWithIdentifier:forIndexPath:];
// 復用 Section 的 Header/Footer:
- [UITableView registerNib:forHeaderFooterViewReuseIdentifier:];
- [UITableView registerClass:forHeaderFooterViewReuseIdentifier:];
- [UITableView dequeueReusableHeaderFooterViewWithIdentifier:];

2. TabelView 代理

2.1 避免快速滑動情況下開過多線程。

cell中的圖片開線程異步加載SDWebImage(異步操作)。但是線程開過多了會造成資源浪費,內存開銷過大。圖片過多時可以不要一滾動就走cellForRow方法,可以在scrollview的代理方法中做限制,當滾動開始減速的時候才加載顯示在當前屏幕上的cell(通過tableview的dragging和declearating兩個狀態也能判斷)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    //如果沒有取到,就初始化
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    cell.textLabel.text = @"Name";

    BOOL canLoad = !self.tableView.dragging && !_tableView.decelerating;
    if  (canLoad) {
        //開始loaddata,異步加載圖片
        NSLog(@"開始加載圖片");
    }
    return cell;
}

// 滾動停止時,觸發該函數
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //刷新tableview
   // [self.tableView reloadData];

 //在此刷新的是屏幕上顯示的cell的內容
    NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
    //獲取到的indexpath為屏幕上的cell的indexpath
    [self.tableView reloadRowsAtIndexPaths:visiblePaths withRowAnimation:UITableViewRowAnimationRight];

}

3. 圖片圓角

3.1 layer.cornerRadius

imageView.layer.cornerRadius = imageView.frame.size.width/2.0;  
// 隱藏邊界
imageView.layer.masksToBounds = YES;

3.2 頭像使用蒙版+貝塞爾曲線加圓角

CAShapeLayer *layer = [[CAShapeLayer alloc] init];

UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.icon.width / 2, self.icon.height / 2) radius:self.icon.width / 2  startAngle:0 endAngle:M_PI * 2 clockwise:YES];

layer.path = path.CGPath;
self.icon.layer.mask = layer;

3.3 stackoverflow

UIImageView *iconImage = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [self.view addSubview:iconImage];

    // Get your image somehow
    UIImage *image = [UIImage imageNamed:@"image.jpg"];
    // Begin a new image that will be the new image with the rounded corners
    // (here with the size of an UIImageView)
    UIGraphicsBeginImageContextWithOptions(iconImage.bounds.size, NO, [UIScreen mainScreen].scale);
    // Add a clip before drawing anything, in the shape of an rounded rect
    [[UIBezierPath bezierPathWithRoundedRect:iconImage.bounds cornerRadius:10.0] addClip];
    // Draw your image
    [image drawInRect:iconImage.bounds];
    // Get the image, here setting the UIImageView image
    iconImage.image = UIGraphicsGetImageFromCurrentImageContext();
    // Lets forget about that we were drawing
    UIGraphicsEndImageContext();

4. 異步加載圖片

第一種方法: SDWebImage的使用

[imageView sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            imageView.image = image;
}];

5 優化UITableViewCell高度計算

Tip
1. 使用不透明視圖, 如非必要, 可以設置opaque為yes;
2. 圖片的alpha盡量不設置透明度;
3. cellForRowAtIndexPath不要做耗時操作, 
   * 讀取文件/寫入文件;
   * 盡量不要去添加和移除view;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,619評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,155評論 3 425
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,635評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,539評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,255評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,646評論 1 326
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,655評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,838評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,399評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,146評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,338評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,893評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,565評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,983評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,257評論 1 292
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,059評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,296評論 2 376

推薦閱讀更多精彩內容

  • tableview的優化一直是一個很考驗基本功的活兒,之前做項目的適合被這個問題困擾了很久,通過性能工具、查閱文檔...
    青蔥烈馬閱讀 4,467評論 1 7
  • 1.UITableViewCell重用機制? UITableView只會創建一屏幕(或者一屏幕多一點)的cell,...
    香蕉你個菠蘿閱讀 3,735評論 0 2
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,158評論 4 61
  • 關于為什么設置視圖不透明可以參考本人Instruments性能檢測里面的第6條:Core Animation:核心...
    和玨貓閱讀 2,110評論 5 24
  • 近來一個月,開始每天做飯,照顧骨折男票,錘煉廚藝,從廚房小白室友救場變得可以獨擋一面。今天燒的紅燒雞塊,如...
    多肉在飛閱讀 240評論 3 1