1

I'm having an issue trying to load an array of images into a UITableView with a prototype cell in another view controller.

I didn't seem to get an answer from swift 3 error : Argument labels '(_:)' do not match any available overloads as I am pretty new and couldn't derive the explanation from the answers.

I am receiving the error in the title from:

let portraitsOfHeroes:[UIImage] = UIImage(named: "picture1", "picture2", "picture3")

while trying to make an array of images with (portraitsOfHeroes):

import UIKit

class NewHeroVC: UIViewController, UITableViewDataSource {

let listOfHeroes:[String] = ["Name1", "Name2", "Name3"]
let portraitsOfHeroes:[UIImage] = UIImage(named: "picture1", "picture2", "picture3")

and use them through (cell.newHeroPortrait.image):

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "heroCell", for: indexPath) as! NewHeroCell
    cell.newHeroName.text = listOfHeroes[indexPath.row]
    cell.newHeroPortrait.image = portraitsOfHeroes[indexPath.row]
    return cell
}

What's the reason it's returning the error on my array?

Community
  • 1
  • 1
Meekswel
  • 33
  • 4

2 Answers2

1

I think you need

let portraitsOfHeroes:[UIImage] = [UIImage(named: "picture1"), UIImage(named: "picture2"), UIImage(named: "picture3")
adamfowlerphoto
  • 2,708
  • 1
  • 11
  • 24
  • That worked thank you so much! What was wrong with my array line? Edit: Hey having to repeat the bit "UIImage(named: "...")" over and over seems tedious. Is there a better way to construct that line of code? – Meekswel May 18 '17 at 22:46
1

Your issue is that UIImage(named:) can only take one name and it only returns a single image. You need to create separate UIImage instances for each image name.

If you want to avoid typing the UIImage(named:) part over and over, you can use flatMap and the array of file image names:

let portraitsOfHeroes:[UIImage] = ["picture1", "picture2", "picture3"].flatMap { UIImage(named: $0) }

The benefit of this approach is that it deals with missing images. If UIImage(named:) returns a nil image for a given image name, that image simply doesn't appear in the array.

rmaddy
  • 314,917
  • 42
  • 532
  • 579