如何在swift中将图像添加到我的表格单元格?

我正在学习本教程 ,我正在为每个json条目创建单元格。 没有照片,一切正常:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("CELL") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL") } let user:JSON = JSON(self.items[indexPath.row]) // print(user) let picURL = "/Users/K/Desktop/aproject/apps/address/addr/Images.xcassets/TabMap.imageset/up_dark.png"//just for tests - some random png let url = NSURL(string: picURL) let data = NSData(contentsOfURL: url!) cell!.textLabel?.text = user["description"].string // cell?.imageView?.image = UIImage(data: data!) return cell! } 

,但是当我添加照片时(取消注释此行):

 cell?.imageView?.image = UIImage(data: data!) 

然后我收到错误:

在此处输入图像描述

 fatal error: unexpectedly found nil while unwrapping an Optional value 

我的计划是传递一个url而不是硬编码的照片(所以使用user["photo"]而不是链接),但对于测试我将url粘贴到我的自定义图形。

如何在文本旁边添加它?

几件事:

为什么之前的行有“ cell! ”,注释掉的行是“ cell? ”。 另外,这是一个表视图子类吗? 您确定您的imageViewsockets已连接吗?

更重要的是,您应该在加载图像数据时进行错误检查。

那是:

 if let data = NSData(contentsOfURL: url!) { cell!.imageView?.image = UIImage(data: data) } 

对于本地图像:

 cell!.imageView?.image = UIImage(named:"ImageName")