0

Cannot convert value of type 'UIImage' to expected argument type 'String'

I am trying to create a book, and if I type in the name of the picture I want in the UIImageView constructor which is "cup", my program executes correctly and displays the same picture on every page. If I try and do "imageNames[element]" to get all my pictures displayed depending on page within my for loop it says it can not convert UIImage to String

      var imageNames: [UIImage] = [
         UIImage(named: "open")!,
         UIImage(named: "cup")!
      ]




        for element in 0 ..< imageNames.count {

        let vc = UIViewController()
        vc.view.backgroundColor = randomColor()

        //Where error is occurring!
        let imageView = UIImageView(image: UIImage(named: 
        imageNames[element]))
        vc.view.addSubview(imageView)
        }

I would think that imageNames[element] would give me the String value in the array. My goal is that when I open the book.... "open" picture is on the first page, and "cup" picture is on the second page.

1 Answer 1

1

Just use an array of strings rather than images

 let imageNames = ["open", "cup"]

 for imageName in imageNames { // no reason for an index based loop

    let vc = UIViewController()
    vc.view.backgroundColor = randomColor()

    let imageView = UIImageView(image: UIImage(named: imageName))
    vc.view.addSubview(imageView)
}

Or if you really want an array of images

 let images = [
     UIImage(named: "open")!,
     UIImage(named: "cup")!
 ]

 for image in images { // no reason for an index based loop

    let vc = UIViewController()
    vc.view.backgroundColor = randomColor()

    let imageView = UIImageView(image: image)
    vc.view.addSubview(imageView)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow I thought I did that already, I have been on this for at least 2 hours. That is exactly what I needed though. Appreciate it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.