user3766930
user3766930

Reputation: 5829

How can I add an image to my table cell in swift?

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:

enter image description here

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?

Upvotes: 1

Views: 9109

Answers (2)

tuledev
tuledev

Reputation: 10317

For the local image:

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

Upvotes: 3

Michael Dautermann
Michael Dautermann

Reputation: 89509

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)
}

Upvotes: 2

Related Questions