Reputation: 496
Im trying to find the UIImageViews in the view and to assign few images to them based on the tags. But unfortunately i couldn't assign the images to UIImageView variable from an array. I couldn't really resolve the problem.
Below is the code that 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 will be appreciated. Thanks in advance.
Upvotes: 3
Views: 2223
Reputation: 42325
First, you're accessing your array with an index outside its bounds. Your for
loop should be from 0
up 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're trying to find a UIImageView
in your self.view.subviews
, right? When you do that, you're setting imageViewSlot
to a UIView
. I see that you're checking if it's a member of class UIImageView
, but that doesn't actually change the type of the imageViewSlot
variable. You'll need to cast imageViewSlot
to a UIImageView
to be able to set the image
property.
I'd 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 setup correctly, then you really don't need that inner for
loop either. You can simplify it to 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
}
}
}
Upvotes: 0
Reputation: 1960
var imageViewSlot = UIImageView()
you gave this as global, and you used same name in for in statement that is the main problem. So because of this it donot know which type of object this is, So for that we have to mention like this (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
}
}
}
}
Upvotes: 3