1

My problem is that based on the number of groups a person has I want to dynamically create that many UIImageView and assign them to the view. I know how to create a single UIImageView and put it onto the view but how can I create a variable number of them since creating another with the same name seems to just overwrite the original? I tried sending the UIImageView into an Array but got an optional error.

            circleView = UIImageView(frame:CGRectMake(125, y, 75, 75))
            y+=150
            circleView.image = UIImage(named:"circle.png")
            circleView.tag = i
            self.view.addSubview(circleView)
            circleArray[i] = circleView

2 Answers 2

1

The problem is that you keep reusing the same circleView instance. When you add it to the array, you are just adding a reference to it. You then reinitialize it, which wipes it out. I also don't see where you are incrementing i. Try something like this:

var circleArray = Array<UIImageView>()
var y : CGFloat = 0.0
var i = 0
circleArray.append(UIImageView(frame:CGRectMake(125, y, 75, 75)))
var circleView = circleArray[i]
circleView.image = UIImage(named:"circle.png")
circleView.tag = i
self.view.addSubview(circleView)

y+=150
i += 1
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use circleArray.append(circleView)

2 Comments

Wow can't believe I made that mistake thanks for catching it!
Even with the correct syntax it seems to be throwing the same optional error. Any thoughts?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.