【问题标题】:Unable to bind image url from JSON(API) to tableviewcell using Swift无法使用 Swift 将图像 url 从 JSON(API) 绑定到 tableviewcell
【发布时间】:2015-08-26 12:45:28
【问题描述】:

以下是来自 API 的示例 JSON 数据。我想使用 swift 在 tableviewcell 中显示 "ArticleTitle""ImageURL" ..

"ArticleTitles":[{"ArticleID":"872",
 "ArticleTitle":"IS 'NOTHlNGNESS' AN EXPERIENCE ?",  
 "Author":"Asampoorna",
 "ImageURL":"http://motherofall.org/sites/default/files/blog/Ignorance.png"
},{..........}]

【问题讨论】:

    标签: ios json swift tableviewcell


    【解决方案1】:

    在响应中,您将获得结果数组。然后在你试图用数组本身来做一些事情之后,这是错误的。得到结果数组后,所有的处理都应该在 cellForRowAtIndexPath 方法中完成。

    将结果数组作为全局而不是tableData和imageData。

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
        let arr:NSArray! = NSArray()
        let dict = arr[indexPath.row] as! NSDictionary
        cell.textLabel?.text = dict["ArticleTitle"] as? String
    
        //Load the image here with image URL string dict["ImageURL"] as? String
    
        return cell
    
    }
    

    并关注this的帖子在tableViewCell中异步加载图片。

    使用以下代码将图像加载到 tableview 单元格内的图像视图。

    if let url = NSURL(string: "http://motherofall.org/sites/default/files/blog/Ignorance.png") {
        if let data = NSData(contentsOfURL: url){
            cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
            cell.imageView.image = UIImage(data: data)
        }
    }
    

    【讨论】:

    • 您好,开发者,我们可以将单个 URL 或单个图像绑定到 UI 。但我们的问题是我们无法将 JSON URL 数组(从我们的 API 端点消费)绑定到 UI。上面是我们的 JSON 数组的结构。
    • 我认为您正在获取一系列字典。循环该数组并获取图像的 URL。然后加载图片。
    • 对不起.. 不需要循环。当您在表格视图单元格中填充图像时,在 cellForRowAtIndexpath 方法中,使用“indexPath.row”作为索引从数组中获取字典。然后你可以获取图像 URL 和上面的代码。
    • 开发者您好,感谢您的回复。我是快速编程的新手。我不明白我在哪里做错了。请看我的代码drive.google.com/file/d/0B8jxqQxSyqksY1N1OXZzX2hpQlU/…
    • 请不要介意。你能给我一个端到端的解决方案来解决我的问题吗?您能否提供一个示例应用程序来使用此 API 在 UITableView 中显示国家(名称)和标志(图像)androidbegin.com/tutorial/jsonparsetutorial.txt
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多