我有一个Json文件,有一个这样的项目:"图像":" https://xxxxxxxxxxx.jpg"
所以我试试这个:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell : TableViewCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
let strName : NSString=arrDict[indexPath.row] .valueForKey("name") as! NSString
let strSubtitle : NSString=arrDict[indexPath.row] .valueForKey("subtitle") as! NSString
let strLocation : NSString=arrDict[indexPath.row] .valueForKey("location") as! NSString
let strStart : NSString=arrDict[indexPath.row] .valueForKey("start") as! NSString
// let strImage : NSString=arrDict[indexPath.row] .valueForKey("image") as! NSString
// let strImage : NSData=arrDict[indexPath.row] .valueForKey("image") as! NSData
let strImage : UIImage=arrDict[indexPath.row] .valueForKey("image") as! UIImage
cell.lbName.text=strName as String
cell.lbSubtitle.text=strSubtitle as String
cell.lbStart.text=strStart as String
cell.lbLocation.text=strLocation as String
cell.lbImage.image=strImage as UIImage
return cell as TableViewCell
}
运行此消息后显示:
无法转换类型' __ NSCFString' (0x1112ca090)到' UIImage' (0x11222b800)。
谢谢。
答案 0 :(得分:1)
问题出在这一行let strImage : UIImage=arrDict[indexPath.row] .valueForKey("image")
..
我确信您的arrDict[indexPath.row].valueForKey("image")
会返回String ...所以您无法将其直接转换为UIImage ..
if let strImage = arrDict[indexPath.row]["image"] as? String{
// ... your strImage is String ...
if let data = NSData(contentsOfURL: NSURL(string:strImage )) {
cell.lbImage.image = UIImage(data: data)
}
}
您的问题的第一行建议"图像":" https://xxxxxxxxxxx.jpg" ..所以通过转换您的网址获取图片Sting to NSURL并下载图片
您可以使用SDWebImage显示来自URL https://github.com/rs/SDWebImage的图像,或者您可以将NSData类与contentsOfURL一起使用
有关详情,请查看this link
答案 1 :(得分:0)
问题是
www.domain.com/news
您正尝试使用let strImage : UIImage=arrDict[indexPath.row] .valueForKey("image") as! UIImage
强制String
投射UIImage
,只有在100%确定时才应使用as! UIImage
。
而是用
替换它!
但在你的情况下,if let image = arrDict[indexPath.row] .valueForKey("image") as? UIImage {
//Now you have a UIImage
}
不是UIImage
所以
String
答案 2 :(得分:0)
麻烦是用朋友的代码和说明解决的。谢谢。
if let strImage = arrDict[indexPath.row]["image"] as? String{
// ... your strImage is String ...
if let data = NSData(contentsOfURL: NSURL(string:strImage )) {
cell.lbImage.image = UIImage(data: data)
}
}