Esko918
Esko918

Reputation: 1469

Setting the constraints of a views subviews without knowing the amount of subviews there are

So my view is pretty simple to setup but I can't figure out how to do a specific task.

So what I need to do is take in an array of strings, each one of these strings are a country ISO3 format code which in turn have a corresponding flag associated with it. Now after I add the flags to the view I need to be able to set all the constraints.

So first I add the imagesviews to the view, that works fine but now when I get to the updateConstraints method I am unsure how to proceed since I have an unknown amount of subviews.

So each subview will be placed about 5 spaces apart from the flag before it and the top of the image and bottom of the image should span the views height.

How can I write code that handles an arbitrary number of subviews?

Upvotes: 0

Views: 33

Answers (1)

matt
matt

Reputation: 535138

So first i add the imagesviews to the view

As you do that, also add each view's constraints. Since you are looping through the flags / image views, you know whether there was a previous image view and if you've taken a little care, you have a reference to it. Thus, there is actually not a lot of code — it's a loop, and not a very long one — and it isn't at all difficult.

As an alternative, I suppose you could use a UIStackView (if you are not running on iOS 8). It will just take all the image views and space them out with constraints for you; all you have to do is decide on its size, which you can presumably do by counting the image views.

Upvotes: 1

Related Questions