如何将Json数组指向本地图像?

时间:2015-04-24 00:45:33

标签: swift xcode6

我是新手,所以很抱歉,如果这是基本的,但我正在尝试在json文件中使用数组并让它指向我的资产库中的图像,但我遇到了问题。其写作: [   {   “形象”:“悍妇”   }, ]

将它写成字符串是错误的吗?我是否需要使用特定代码将字符串转换为我的图像名称?

感谢您提供的任何帮助!

编辑:

我得到的错误是在线     TrackPic.image = image

“使用未解析的标识符'TrackPic'”

class QuizModel: NSObject {

func getQuestions() -> [Question] {

    // Array of question objects
    var questions:[Question] = [Question]()

    // Get Json array of dictionaries
    let jsonObjects:[NSDictionary] = self.getLocalJsonFile()

    // Loop through each dictionary and assign values to our question objs
    var index:Int
    for index = 0; index < jsonObjects.count; index++ {

        // Current JSON dict
        let jsonDictionary:NSDictionary = jsonObjects[index]

        // Create a question obj
        var q:Question = Question()

        let imageName = jsonDictionary["image"] as! String
        let image = UIImage(named: imageName)
        TrackPic.image = image


        // Assign the values of each key value pair to the question object
        q.image = jsonDictionary["image"] as! String
        q.questionText = jsonDictionary["question"] as! String
        q.answers = jsonDictionary["answers"] as! [String]
        q.correctAnswerIndex = jsonDictionary["correctIndex"] as! Int
        q.module = jsonDictionary["module"] as! Int
        q.lesson = jsonDictionary["lesson"] as! Int
        q.feedback = jsonDictionary["feedback"] as! String


        // Add the question to the question array
        questions.append(q)
    }

    // Return list of question objects
    return questions
}

1 个答案:

答案 0 :(得分:0)

首先需要像json一样从json获取图像名称

let imageName = jsonDictionary["image"] as! String

(如果您想确定正在正确解析JSON,请确保将imageName写入控制台)

然后你需要用UIImageUIImage(named: String)初始化你的图像名称来自json所以

let image = UIImage(named : imageName)

然后你有你的形象,你可以把它放在UIImageView

我想在你的情况下,这将是

q.image = image

如果qUIImageView