0

This is inside my viewForHeaderInSection. That means, this happens through each section.

for i in 0..<mySections[section].items!.count {
                print("Valid For \(mySections[section].items[i]).")

                let imagesArray = [header.icon1, header.icon2, header.icon3, header.icon4, header.icon5]  

                imagesArray[i].image = UIImage(named: "IconHamburger")

            }

So for each section, I get the values for "Valid For".

E.g. Section 1 gets

  • Valid For ABC.
  • Valid For PQR.
  • Valid For XYZ.

Section 2 gets

  • Valid For ABC.
  • Valid For XYZ.

and so on...

My question is how do I assign image name to the images in my imagesArray? With condition like -

if Valid For is ABC, image name is "ImageAbc"

if Valid For is PQR, image name is "ImagePqr"

With my current code snippet above, all my image outlets get "IconHamburger" assigned.

Also, I have 5 images in my array and, the "Valid For" items are always <= 5. So if I get 3 "Valid For" items, images need to be assigned only for the first three images.

Current output Screenshot from a section here -

enter image description here

Lohith Korupolu
  • 1,066
  • 1
  • 18
  • 52

1 Answers1

1

It doesn't seem like you're very far off from what you're describing. Maybe this?

for i in 0..<mySections[section].items!.count {
    let validItems = mySections[section].items[i]
    let imagesArray = [header.icon1, header.icon2, header.icon3, header.icon4, header.icon5]

    // Map your items to your image name formats (ABC -> ImageAbc)
    let validImageNames = validItems.map { "Image" + $0.lowercased().capitalized }

    // Update images in your image array
    validImageNames.enumerated().forEach { index, imageName in

        // Check for index in range
        guard index < imagesArray.count else { return }

        // Update image
        imagesArray[index].image = UIImage(named: imageName)
    }
}
tbogosia
  • 315
  • 1
  • 10
  • that's exactly what I was looking for. Was not aware of the .forEach syntax. Thanks. – Lohith Korupolu Jun 28 '17 at 10:59
  • Any chance you can take a look at https://stackoverflow.com/questions/44718598/swift-tableview-row-height-updates-only-after-scrolling-or-toggle-expand-colla :( I also have a bounty of 50 for this question :P – Lohith Korupolu Jun 28 '17 at 10:59
  • For sure! I also realized I was missing `enumerated()` above, which gives you the indices of the elements. Alternatively you could also use `for (index, imageName) in validImageNames.enumerated() { ... }` but I personally like the `.forEach` syntax – tbogosia Jun 28 '17 at 11:01
  • yes, I read about forEach after going through you answer and realized about having enumerated() – Lohith Korupolu Jun 28 '17 at 11:05