"Unable to assign image to * UIImageView *" Error in SWIFT (iOS)
I am trying to find UIImageViews in a view and assign multiple images to them based on tags. But unfortunately I couldn't assign the images to the UIImageView variable from the array. I couldn't solve the problem.
Below is the code I wrote.
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
}
}
}
}
Any help would be appreciated. Thanks in advance.
source to share
- in the above code,
var imageViewSlot = UIImageView()
you specified it as global and you used the same name in the statement for , which is the main problem. Therefore, because of this, he does not know what type of object it is. So for this we have to mention how to do it(imageViewSlot as UIImageView).image = image
try below code and check 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
}
}
}
}
source to share
First, you access your array with an index outside of its bounds. Your cycle for
should be from 0
to and not including imagePieces.count
.
for i in 0..<imagePieces.count
{
if (imageViewSlot.tag == i)
{
imageViewSlot.image = imagePieces[i] as? UIImage //Error in this line
}
}
Second, it looks like you are trying to find UIImageView
in yours self.view.subviews
, right? When you do, you set imageViewSlot
to UIView
. I can see that you are checking if it is a member of the class UIImageView
, but that does not actually change the type of the variable imageViewSlot
. You will need to point to imageViewSlot
in UIImageView
order to set the property image
.
I would do it like this (untested):
// 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
}
}
}
}
If your tags are set up correctly, you really don't need this inner loop for
. You can simplify it something like this:
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
}
}
}
source to share