John Murcielago John Murcielago - 4 months ago 10
Swift Question

Custom UITableViewCell with optionals

I'm creating custom cell for my

tableView
. I made a swift file:

import Foundation
import UIKit

class CellForPost: UITableViewCell {
@IBOutlet weak var postLikes: UILabel!
@IBOutlet weak var postText: UILabel!
@IBOutlet weak var postDate: UILabel!
@IBOutlet weak var postPhoto: UIImageView!
}


and implemented it in delegate method:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("postCell", forIndexPath: indexPath) as! CellForPost
cell.postPhoto.image = UIImage.init(data: (posts[indexPath.item].postPhoto)! as NSData)
cell.postText.text = posts[indexPath.item].postText
cell.postLikes.text = String(posts[indexPath.item].postLikes!)
cell.postDate.text = timestampToDate(posts[indexPath.item].postDate!)
return cell
}


everything works great when post has full content, but when for example there is no photo(which is optional in
post
struct) it crashes with message


fatal error: unexpectedly found nil while unwrapping an Optional value


I understand this message, so I tried to make

@IBOutlet weak var postPhoto: UIImageView?


like an optional value, but it doesn't work, 'cos compiler wants me to unwrap values before inserting to cell.
P.S. If it's possible to give a short advice about deleting
imageView
at all when it is nil and resize row height to fit.

Answer

You need to check that your object has value before assigning it to the IBOutelet. You need to change your cellForRowAtIndexPath something like this

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("postCell", forIndexPath: indexPath) as! CellForPost
    if let data = posts[indexPath.item].postPhoto) as? NSData {
        cell.postPhoto.image = UIImage.init(data: data)
    }
    else {
        cell.postPhoto.image = nil
    }
    if let postText = posts[indexPath.item].postText) as? String {
        cell.postText.text = postText
    }
    else {
        cell.postText.text = ""
    }
    if let postLikes = posts[indexPath.item].postLikes) as? Int {
        cell.postLikes.text = String(postLikes)
    }
    else {
        cell.postLikes.text = ""
    }
    if let postDate = posts[indexPath.item].postDate) as? NSDate {
        cell.postDate.text = timestampToDate(postDate)
    }
    else {
        cell.postDate.text = ""
    }
    return cell
}

Hope this will help you.

Comments