Miles Miles - 1 month ago 8
iOS Question

How to set UIImageView.image property in UITableViewCell

I am having a problem trying to show an array of images on each cell, for a tableview.

I have a separate

TableViewCell
Swift file where I have a
UIImage
on the cell linked up. The outlet is named:
CellVenueImage


For some reason when I try to implement the image on my TableView view controller, I get an error that says:
Value of type 'TableViewCell' has no member 'CellVenueImage'


Here is the line in which that happens:

cell.CellVenueImage.image = imagename


Using Swift 3.

Here is the code for the TableView:

import UIKit

class VenueTableViewController: UITableViewController {


let VenueImageList = ["1970s.png","1980s.png","1990s.png"]

override func viewDidLoad() {
super.viewDidLoad()


}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return VenueImageList.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "VenueCell", for: indexPath) as! TableViewCell

let imagename = UIImage(named: VenueImageList[indexPath.row])
cell.CellVenueImage.image = imagename

return cell
}


TableViewCell code:

import UIKit

class VenuesTableViewCell: UITableViewCell {

@IBOutlet weak var CellVenueImage: UIImageView!

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

Answer

The mistake is, that you're not using your created TableViewCell Subclass, you are using a regular UITableViewCell.

let cell = tableView.dequeueReusableCell(withIdentifier: "VenueCell", for: indexPath) as! TableViewCell

You need to cast it as your UITableViewCell subclass.

If it is called "VenuesTableViewCell", for example: class VenuesTableViewCell: UITableViewCell {, then cast it as VenuesTableViewCell.

let cell = tableView.dequeueReusableCell(withIdentifier: "VenueCell", for: indexPath) as! VenuesTableViewCell
Comments