无法使用 Swift 将图像 url 从 JSON(API) 绑定到 tableviewcell

Posted

技术标签:

【中文标题】无法使用 Swift 将图像 url 从 JSON(API) 绑定到 tableviewcell【英文标题】:Unable to bind image url from JSON(API) to tableviewcell using Swift 【发布时间】: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"
,..........]

【问题讨论】:

【参考方案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

以上是关于无法使用 Swift 将图像 url 从 JSON(API) 绑定到 tableviewcell的主要内容,如果未能解决你的问题,请参考以下文章

Swift 3将图像从URL添加到UIImageView [重复]

从 alamofire swift 的 tableview 单元格中的 url 加载图像

Swift:使用 UIImageView 显示带有从数组 [0..4] 中获取的 URL 的图像

将图像从 URL 保存到库,重命名并使用 Swift 共享它

从 URL 加载图像并使用 Swift4 将它们存储在本地

Swift Custom Response Serializer 随机返回图像