如何快速将图像添加到我的表格单元格? [英] How can I add an image to my table cell in swift?
问题描述
我正在关注
fatal error: unwrapped an Optional value 时意外发现 nil
我的计划是传递一个 url 而不是硬编码的照片(因此使用 user["photo"]
而不是链接),但为了测试,我将 url 粘贴到我的自定义图形中.
如何将其添加到文本旁边?
一些事情:
为什么前面的行有cell!
"而注释掉的行是cell?
".另外,这是表视图子类吗?您确定您的 imageView 插座已连接?
更重要的是,您应该在加载图像数据时进行错误检查.
即:
if let data = NSData(contentsOfURL: url!){cell!.imageView?.image = UIImage(data: data)}
I'm following this tutorial and I'm creating cells for each json entry. Everything works fine without photos:
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!
}
, but when I add photos (uncomment this line):
cell?.imageView?.image = UIImage(data: data!)
then I'm getting error:
fatal error: unexpectedly found nil while unwrapping an Optional value
My plan is to pass there an url instead of hardcoded photo (so using user["photo"]
instead of the link), but for tests I pasted the url to my custom graphic.
How can I add it next to text?
A couple things:
Why does the line before have "cell!
" and the commented out line is "cell?
". Also, is this a table view subclass? Are you sure your imageView outlet is connected?
More importantly, you should do an error check when loading your image data.
That is:
if let data = NSData(contentsOfURL: url!)
{
cell!.imageView?.image = UIImage(data: data)
}
这篇关于如何快速将图像添加到我的表格单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!