应用程序在变量中设置图像时崩溃

时间:2015-07-04 12:09:27

标签: ios swift

我正在尝试将图像存储在变量中,但我的应用程序在下面给定的行上崩溃了:

let theImage = UIImage(named: self.arrImages[indexPath.row])!

此处,arrImages是一个包含图像的数组。

我得到的崩溃是

  

致命错误:在展开“可选值”时意外发现nil

修改1 根据@Duncan C& C的要求@Valentin 的声明:

var arrImages = [String]()

UICollectionView

的委托中使用它
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    if collectionView == self.collectionView
    {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ImageCell

        cell.imageView.image = nil
        var theImage = UIImage()
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {

            if let image = UIImage(named: self.arrImages[indexPath.row]) {
                // Do whatever you like with the image here
                 theImage = UIImage(named: self.arrImages[indexPath.row])!
            }


            dispatch_async(dispatch_get_main_queue(), {

                cell.imageView.image =  theImage
                cell.imageView.contentMode = .ScaleAspectFit

            });
        })

        return cell
    }

2 个答案:

答案 0 :(得分:2)

您没有提供足够的信息,而您所说的一些事情没有意义。

发布arrImages的声明,以及将值安装到数组中的代码。

您说您的数组包含图像,但您的代码期望数组包含图像文件名(字符串)。

接下来,您需要将代码分解为步骤并进行调试:

let index = indexPath.row
let imageName = self.arrImages[index];
println("At index \(index), imageName = \"\(imageName)\"")
let image = UIImage(named: imageName)
println("Image = \(image)")

答案 1 :(得分:0)

尝试用

绑定它
if let image = UIImage(named: ...) {
    // Do whatever you like with the image here  
}