将JSON字符串转换为UIImage [关闭]

问题描述 投票:-2回答:1

我正在寻找一个示例,说明如何根据从JSON响应传递的字符串显示特定的UIImage(保存在资产目录中)。

例如。如果database_field选择了“Balloons”,它将不会显示单词“Balloons”,而是将其转换为显示图像“Balloons”。我已经尝试使用switchcase将String更改为图像,但会得到各种编译错误。

编辑

我正在寻找什么,以及我无法工作(因为我是switch的新手......!)是以下代码:

        if let imgType = bug.bugType {

        var imgTypeImageName = ""
        switch imgType {
        case "Ballons":
            imgTypeImageName = "Balloons"
            break
        case "Apple":
            imgTypeImageName = "Apple"
            break
        default:
            imgTypeImageName = "default"
            break
        }

        imgIconImage.image = UIImage(named: imgTypeImageName)
    }

希望这有助于某人!

ios json swift uiimage
1个回答
1
投票

只需使用initializer for UIImage that accepts a string for the image name。这是一个示例游乐场。您需要将test.jpg拖入左侧的Resources文件夹中,以使此操场正确运行。

import PlaygroundSupport
import UIKit

let jsonData = """
{
"imageName" : "test.jpg"
}
""".data(using: .utf8)!

struct CustomStruct: Codable {
    let imageName: String
    var image: UIImage? {
        return UIImage(named: imageName)
    }
}

let custom = try! JSONDecoder().decode(CustomStruct.self, from: jsonData)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
imageView.image = custom.image
PlaygroundPage.current.liveView = imageView
© www.soinside.com 2019 - 2024. All rights reserved.