David David - 3 months ago 5
Swift Question

UIImageView.image is nil in my UITableViewCell when I select cell even though I know it should have a value

In my

cellForRowAtIndexPath
function, I set the URL for a UIImageView to load an image from. When this image is loaded, I select the cell, and in
didSelectRowWithIndexPath
the cell's image's image is nil. In fact, even labels are nil. All data is nil as though there is no data in the cell, but I could clearly see the cell visually with the data I want in it.

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Session.sharedInstance.universities.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


let cell = tableView.dequeueReusableCellWithIdentifier("universityCell", forIndexPath: indexPath) as! UniversityTableCell

if (indexPath.row < Session.sharedInstance.universities.count) {

let university = Session.sharedInstance.universities[indexPath.row]
cell.setInfo(university.imageUrl)
}

return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("universityCell", forIndexPath: indexPath) as! UniversityTableCell

// This is nil. But why? I set the data in my cellForRowAtIndexPath method
print(cell.universityImage.image)

}


In my UniversityTableCell:

class UniversityTableCell: UITableViewCell {

@IBOutlet var universityImage: UIImageView!

func setInfo(url: String) {
self.universityImage.setImageWithURL(NSURL(string: url), usingActivityIndicatorStyle: .Gray)
}

override func prepareForReuse() {
super.prepareForReuse()
self.universityImage.sd_cancelCurrentImageLoad()
}
}

Answer

Try to modify your code to

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
      let cell = tableView.cellForRowAtIndexPath(indexPath) as! UniversityTableCell

     // This is nil. But why? I set the data in my cellForRowAtIndexPath method
      print(cell.universityImage.image)

}