jamesCode
jamesCode

Reputation: 1

Iterate through different view with array, Swift

I have 4 different progressView

@IBOutlet weak var firstProgressBar: UIProgressView!
@IBOutlet weak var secondProgressBar: UIProgressView!
@IBOutlet weak var thirdProgressBar: UIProgressView!
@IBOutlet weak var fourthProgressBar: UIProgressView!

And I have an array with 4 values

[30,20,24,25]

Since this array change from the API call (I need to check if I really have this value), what is the best and safer way to:

This is my current code:

func setupProgressBar(item: CustomObject) {
   let array = item.array // [x,y,z,w] array 

   self.progressBar.setProgress( ?? , animated: false)
}

I have an animation for the value but it's not the point of my question, i just need to set values

Upvotes: 0

Views: 211

Answers (2)

Frankenstein
Frankenstein

Reputation: 16341

A better approach would be to connect all the UIProgressBar in your storyboard to an @IBOutlet collection.

@IBOutlet weak var progressBars: [UIProgressView]!

Then iterate through the array to set the value of progressBars.

func setupProgressBar(item: CustomObject) {
    let array = item.array // [x,y,z,w] array
    for (progressBar, value) in zip(progressBars, array) {
        progressBar.setProgress(value, animated: false)
    }
}

Upvotes: 3

Mubashir Ali
Mubashir Ali

Reputation: 359

func setupProgressBar(item: CustomObject) {
    let valueArray = item.array.sorted  // [x,y,z,w] array
    let progressBars = [firstProgressBar, second….., fourthProgressBar]
    for item in valueArray.enumerated() {
        progressBars[item.index].setProgress(item.value)
    }
}

Make sure that progress bars and values are equal. Otherwise the code will crash.

Upvotes: 2

Related Questions