// 0. 佔位圖像 UIImage *placeholder = [UIImage imageNamed:@"user_default"]; cell.imageView.image = placeholder;
layoutSubviews
方法會根據圖像的大小自動調整 imageView
的尺寸cell.nameLabel.text = app.name; cell.downloadLabel.text = app.download; // 異步加載圖像 // 0. 佔位圖像 UIImage *placeholder = [UIImage imageNamed:@"user_default"]; cell.iconView.image = placeholder; // 1. 定義下載操做 NSBlockOperation *downloadOp = [NSBlockOperation blockOperationWithBlock:^{ // 1. 模擬延時 NSLog(@"正在下載 %@", app.name); [NSThread sleepForTimeInterval:0.5]; // 2. 異步加載網絡圖片 NSURL *url = [NSURL URLWithString:app.icon]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data]; // 3. 主線程更新 UI [[NSOperationQueue mainQueue] addOperationWithBlock:^{ cell.iconView.image = image; }]; }]; // 2. 將下載操做添加到隊列 [self.downloadQueue addOperation:downloadOp];
若是網絡圖片下載速度不一致,同時用戶滾動圖片,可能會出現圖片顯示"錯行"的問題網絡
修改延時代碼,查看錯誤app
// 1. 模擬延時 if (indexPath.row > 9) { [NSThread sleepForTimeInterval:3.0]; }
上下滾動一下表格便可看到 cell 複用的錯誤異步