首页 > 解决方案 > Unable to initialise UIImage in TableCellView

问题描述

I am trying to learn Swift so this question might be a little stupid, bear with me please.

I have a function which initialises the properties like this-

private func loadSampleMeals(){
    let photo1 = UIImage(named: "meal1")
    let photo2 = UIImage(named: "meal2")
    let photo3 = UIImage(named: "meal3")

    guard let meal1 = Meal(name: "meal1", photo: photo1, rating: 4) else {
        fatalError("Unable to initialize meal1")
    }

    guard let meal2 = Meal(name: "meal2", photo: photo2, rating: 3) else{
        fatalError("Unable to initialize meal2")
    }

    guard let meal3 = Meal(name: "meal3", photo: photo3, rating: 1) else{
        fatalError("Unable to initialize meal3")
    }

    meals += [meal1, meal2, meal3]
}

Then I am trying to load them to the table cell like-

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier = "MealTableViewCell"

    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MealTableViewCell else {
        fatalError("The dequeued cell is not an instance of MealTableViewCell.")
    }

    let meal = meals[indexPath.row]

    cell.nameLabel.text = meal.name
    cell.photoImageView.image = meal.photo // <- error here
    cell.ratingControl.rating = meal.rating

    return cell
}

I get below error when I assign the image property in the above code-

[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7fa19ed019a0 2018-05-18 14:12:28.845232+0530 FoodTracker[2440:67077] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7fa19ed019a0'

I have added the images and they are in .jpg format with names meal1, meal2 and meal3. But don't know what I am doing wrong. Interestingly I have another image- defaultPhoto in the assists and if I comment out the line above that throws the error, my code runs fine and the emulator shows defaultPhoto image.

Here's how my asset looks like-

enter image description here

Any help with this please? Let me know if I can add more details.

Edit:

My outlets looks like this-

class MealTableViewCell: UITableViewCell {
    //MARK: Properties
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var photoImageView: UIImageView!
    @IBOutlet weak var ratingControl: RatingControl!

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

The problem is just with photoImageView. The other two outlets work fine.

标签: swiftxcodeuitableviewswift3

解决方案


Please check your IBOutlet for UIImageView is binded with your Cell.


推荐阅读