Reputation: 384
I have an int n that holds value. I want to create a loop that will create UIImageViews with consecutive tags.
My code:
var n:Int = 1
if arrayOfEmojis.count != 0 {
for emoji in arrayOfEmojis {
let emojiView = self.view.viewWithTag(n) as! UIImageView
emojiView.image = emoji
...
}
but the emojiView isn't created. When I use "if let emojiView = " it also just not created. Am i using "viewWithTag(n)" func wrong?
_______edit_________
was using .viewWithTag()
wrong, had to just assign a tag with .tag
property.
However, now, I want to get that view using the tag that was assigned.
I figured now i can use .viewWithTag()
func?
I get unexpectedly found nil...
when calling :
(n
was used in previous loop where imageViews was created, and it was updated to the number of imageViews that was created):
if arrayOfEmojis.count != 0 {
for j in 1...n {
var view1 = self.view.viewWithTag(j) as! UIImageView
arrayOfEmojiViews.append(view1)
}
}
Upvotes: 3
Views: 4480
Reputation: 31645
I think you are misunderstanding the purpose of using viewWithTag(_:):
Returns the view whose tag matches the specified value.
It does not create a new instance, it is used for getting a specific identified view based on its tag value.
If I am not mistaking, you want to create new instances, by mentioning:
I want to create a loop that will create UIImageViews with consecutive tags*.
It should be similar to:
var n:Int = 1
var currentTag = 0
if arrayOfEmojis.count != 0 {
for emoji in arrayOfEmojis {
let emojiView = UIImageView(image: emoji)
emojiView.tag = currentTag
currentTag += 1
// don't forget to set the frame for the emojiView
...
}
}
For each iteration, a new instance of UIImageView will be created -by using init(image:) initializer- and setting its tag value "consecutively" based on the current value of currentTag
variable.
Upvotes: 1