Hibernia Hibernia - 1 year ago 93
Swift Question

Looping through subviews swift / ios

var replycount = replies.count
var startingTag = 10

for subview in self.personView.subviews {

if replycount > 0 {
subview.viewWithTag(startingTag)?.backgroundColor = .green
replycount = replycount - 1
startingTag = startingTag + 1


I'm pulling a number from a server (replycount) and trying to represent the number by coloring some views on the screen. I've got 10 bubbles across the bottom, and if replycount was 4, starting from the left I'd want 4 of the bubbles to have a green background color, and the rest to remain their default black.

What I'm trying to do with the above code is to grab the reply count which I"m doing successfully, my first bubble starts at a tag of 10 and goes up to 19, and if the reply count is more than 0, meaning there is a reply, I'm wanting to take the first tag of 10, make it green, then move on to the next tag of 11, minus from the reply count, and keep going until there are no more replies.

The only time the code below works is if I comment out

replycount = replycount - 1

and change viewWithTag(startingTag) to viewWithTag(10) and hardcode in the number. If either of those two things aren't done the view's color is not changed.

Is there a better way to do this, or any ideas why I'm running into this issue?

Answer Source

Skip looping through subviews and just do self.view.viewWithTag? Although I'm just assuming all of the bubbles are in the same view, and not each in a different subview.

Although I would probably have written it something like this for clarity:

var replycount = replies.count

for tag in 10 ..< (10 + replycount) {
  self.view.viewWithTag(tag)?.backgroundColor = .green
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download