2017-01-22 49 views
0

如果与单元格关联的文件位于设备上,我试图添加图像并将其添加到collectionView单元格。如果文件存在,将图像添加到collectionView单元

该文件在那里,所以下面的代码取消隐藏图像,但是我得到一个错误,它发现零试图展开可选。

什么是错的代码什么想法?

enter image description here

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell: JourneyCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! JourneyCollectionViewCell 

    // query if file is on LDS and add image to indicate 
    let cellPartName = self.partArray[indexPath.item].name 
    let checkQuery = PFQuery(className: "downloadedAudio") 
     checkQuery.whereKeyExists(cellPartName) 
     checkQuery.fromLocalDatastore() 
     checkQuery.getFirstObjectInBackground(block: { (object, error) in 
      if error != nil || object == nil { 
       print("The file does not exist locally on the device, hide the image.") 
       //cell.ImageDownloaded.image = UIImage(named: "") 

       // crashes on this line 
       cell.ImageDownloaded.isHidden = true 
      } else { 
       print("the file already exists on the device, show the image.") 
       //cell.ImageDownloaded.image = UIImage(named: "download") 

       // crashes on this line 
       cell.ImageDownloaded.isHidden = false 
      } 
     }) 


    return cell 

} 




the file already exists on the device, show the image. 
fatal error: unexpectedly found nil while unwrapping an Optional value 
(lldb) 

图像 “下载” 是磁带。

+0

'cell'的定义在哪里? – BallpointBen

+0

崩溃说什么?大部分细节都是有用的。 – raidfive

+0

我似乎没有在您的方法中定义任何'cell'变量。你忘记了离队吗? 'let cell = collectionView.dequeueReusableCell(withReuseIdentifier:reuseIdentifier,for:indexPath);' – ilbesculpi

回答

2

一个快速的注意。在声明一个变量时,你应该总是使用camelCase。因此,ImageDownloaded应该是imageDownloaded

在这里代码非常几行,它似乎崩溃在这条线:

cell.ImageDownloaded.isHidden = false 

这意味着变量ImageDownloaded大概是nil变量。根据我的经验,这可能是由于您的单元类的代码中声明了变量,但关联的UIImageView未连接到声明。因此,从故事板看,它看起来像是存在的,并且从代码看它存在,但是当你尝试访问它时突然中断。

如果您删除并将其中任一部分粘贴回来,可能会发生这种情况。它看起来相同,但连接不再存在。要解决它,只需控制 - 再次拖动到代码声明旁边的空圈。

+0

你是对的。我是一个木偶,从界面生成器到我的课程的链接被打破了。 – Pippo

相关问题