2017-08-01 71 views
1

我试图做一个表格,当图像完成加载(异步)时,单元格上的imageView将alpha从0更改为1。 我做了什么似乎只是将图像显示在一个而不是淡入。我确定它是某种竞争条件,但我是iOS新手,并且不知道如何解决这个问题。任何输入都会很棒。 这里是我的代码:异步加载动画cell.imageview

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 

    //Configure the cell... 
    let episode = episodes[indexPath.row] 

    cell.textLabel?.text = episode.title 

    cell.detailTextLabel?.text = episode.content 

    let logoUrl = URL(string: episode.logoUrl!) 

    if (episode.logoImage == nil){ 
     episode.logoImage = UIImage() 
     DispatchQueue.global().async { 
      let data = try? Data(contentsOf: logoUrl!) //make sure your image in this url does exist, otherwise unwrap in a if let check/try-catch 
      DispatchQueue.main.async { 
       episode.logoImage = UIImage(data: data!) 
       cell.imageView?.image = episode.logoImage 
       self.episodesTable.reloadData() 
       cell.imageView?.alpha = 0 
       UIView.animate(withDuration: 1, animations: { 
        cell.imageView?.alpha = 1 
       }) 

      } 
     } 
    } else{ 
     cell.imageView?.image = episode.logoImage 
    } 

    return cell 
} 
+1

是否需要'self.episodesTable.reloadData()?尝试删除它可能吗? –

回答

1

reloadData()调用导致重装的所有单元格,包括您试图动画之一。我的建议是用它的索引路径标记你的单元格。在异步调用之后,检查它是否仍然呈现正确的数据并在不重新加载整个表格视图的情况下进行动画处理。

// ... 
cell.tag = indexPath.item 
DispatchQueue.global().async { 
    // async load 
    DispatchQueue.main.async { 
     guard cell.tag == indexPath.item else { return } 
     cell.imageView?.alpha = 0.0 
     cell.imageView?.image = image 
     // animate 
    } 
} 
// ... 
+0

你说得对。重新加载是造成这个问题。此外,我创建了一个自定义单元格并为其制作UIImage,而不是使用默认的单元格图像。 – iCediCe

3

请先动画为1

cell.imageView?.alpha = 0 
UIView.animate(withDuration: 1, animations: { 
        cell.imageView?.alpha = 1 
       }) 

而且之前设置透明度为0,你不需要重新加载表。删除self.episodesTable.reloadData()

您正在跨越后台线程并从该线程内的url加载图像。如果在用户滚动单元格之间呢?你将在错误的单元格上留下错误的图像(因为单元格重用,那就是)。

我的建议是使用SDWebImageCache,并使用它的完成块为alpha生成动画。

// Changing animation duration to 0.2 seconds from 1 second 
if(cacheType == SDImageCacheTypeNone) { 
    cell.imageView?.alpha = 0 
    [UIView animateWithDuration:0.2 animations:^{ 
     cell.imageView?.alpha = 1; 
    }]; 
} 
+1

你是对的。然而,这是在我的代码准备好了,不知道它是如何迷失在这个问题。但是这并不能解决图像仍然不能淡入的问题,只是出现。我用缺失的一行来解决问题。 – iCediCe