"无法将图像分配给* UIImageView *" SWIFT(iOS)出错

时间:2014-10-15 05:19:35

标签: ios swift uiimageview

我试图在视图中找到UIImageViews,并根据标签为它们分配一些图像。但不幸的是,我无法将图像分配给数组中的UIImageView变量。我无法真正解决问题。

以下是我写的代码。

var imageViewSlot = UIImageView()
    for imageViewSlot in self.view.subviews
    {
       if (imageViewSlot .isMemberOfClass(UIImageView))
       {
            for i in 1...imagePieces.count
            {
                if (imageViewSlot.tag == i)
                {
                    imageViewSlot.image = imagePieces[i] as? UIImage //Error in this line
                }
            }
        }
    }

任何帮助将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:3)

  • 在上面的代码var imageViewSlot = UIImageView()中,您将此视为全局代码,并且您在 for 语句中使用相同的名称作为主要问题。因此,它不知道这是什么类型的对象,所以我们必须提到这样(imageViewSlot as UIImageView).image = image

尝试下面的代码,然后检查this link

 for  imageViewSlot in self.view.subviews
    {
        if (imageViewSlot .isMemberOfClass(UIImageView))
        {
            for i in 1...imagePieces.count
            {
                if (imageViewSlot.tag == i)
                {
                    var image = UIImage(named: imagePieces[i])
                    (imageViewSlot as UIImageView).image = image

                }
            }
        }
    }

答案 1 :(得分:0)

首先,您访问的数组的索引超出其范围。您的for循环应该从0,包括imagePieces.count

for i in 0..<imagePieces.count
{
    if (imageViewSlot.tag == i)
    {
        imageViewSlot.image = imagePieces[i] as? UIImage //Error in this line
    }
}

其次,看起来您正试图在UIImageView中找到self.view.subviews,对吧?执行此操作后,您将imageViewSlot设置为UIView。我看到你正在检查它是否是类UIImageView的成员,但这实际上并没有改变imageViewSlot变量的类型。您需要将imageViewSlot投射到UIImageView才能设置image属性。

我会这样做(未经测试):

// Note, you don't need to declare var imageViewSlot first

for subview in self.view.subviews {
    if let imageViewSlot = subview as? UIImageView {
        for i in 0..<imagePieces.count {
            if imageViewSlot.tag == i {
                imageViewSlot.image = imagePieces[i] as UIImage
            }
        }
    }
}

如果您的代码设置正确,那么您实际上也不需要内部for循环。您可以将其简化为以下内容:

for subview in self.view.subviews {
    if let imageViewSlot = subview as? UIImageView {
        if imageViewSlot.tag >=0 && imageViewSlot < imagePieces.count {
            imageViewSlot.image = imagePieces[imageViewSlot.tag] as UIImage
        }
    }
}