从UIImage数组获取值并转换为字符串

时间:2019-05-08 20:09:32

标签: arrays swift string xcode uiimage

无法将类型“ UIImage”的值转换为预期的参数类型“字符串”

我正在尝试创建一本书,如果我在UIImageView构造函数“ cup”中输入想要的图片名称,则我的程序将正确执行并在每页上显示相同的图片。如果我尝试执行“ imageNames [element]”以根据我的for循环中的页面显示所有图片,则表示无法将UIImage转换为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)
        }

我认为imageNames [element]会给我数组中的String值。 我的目标是当我打开书本时。...“打开”图片在第一页上,而“杯子”图片在第二页上。

1 个答案:

答案 0 :(得分:1)

只需使用字符串数组而不是图像

 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)
}

或者如果您真的想要一个图像数组

 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)
}