在UITableView單元格中從url加載異步圖像-滾動時將圖像更改為錯誤的圖像我編寫了兩種方法來在我的UITableView單元格中異步加載圖片。在這兩種情況下,圖像將加載良好,但當我滾動表時,圖像將更改幾次,直到滾動結束,圖像將返回到正確的圖像。我不知道為什么會這樣。#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)- (void)viewDidLoad{ [super viewDidLoad]; dispatch_async(kBgQueue, ^{ NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://myurl.com/getMovies.php"]]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; });}-(void)fetchedData:(NSData *)data{ NSError* error; myJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; [_myTableView reloadData];} - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ // Return the number of rows in the section. // Usually the number of items in your array (the one that holds your list) NSLog(@"myJson count: %d",[myJson count]); return [myJson count];} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ myCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if (cell == nil) { cell = [[myCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; } dispatch_async(kBgQueue, ^{ NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg",[[myJson objectAtIndex:indexPath.row] objectForKey:@"movieId"]]]]; dispatch_async(dispatch_get_main_queue(), ^{ cell.poster.image = [UIImage imageWithData:imgData]; }); }); return cell;}
3 回答

躍然一笑
TA貢獻1826條經驗 獲得超6個贊
[self.yourTableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomCell"];
[self.yourTableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"CustomCell"];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath]; cell.imageViewCustom.image = nil; // [UIImage imageNamed:@"default.png"]; cell.textLabelCustom.text = @"Hello"; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // retrive image on global queue UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:kImgLink]]]; dispatch_async(dispatch_get_main_queue(), ^{ CustomTableViewCell * cell = (CustomTableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; // assign cell image on main thread cell.imageViewCustom.image = img; }); }); return cell; }
- 3 回答
- 0 關注
- 537 瀏覽
添加回答
舉報
0/150
提交
取消