icestorm0806
icestorm0806

Reputation: 711

Adding label to a prototype cell

I need to add a label to a prototype cell but I am getting the error "Value of type 'UITableViewCell' has no member 'movieTitleLabel'.

import UIKit

class FirstTableView: UITableViewController {

let model = MovieModel()

override func viewDidLoad() {
    super.viewDidLoad()
}

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return model.MovieArray.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "movieCells", for: indexPath) as! TableViewCell
    cell.movieTitleLabel?.text = model.movieArray[indexPath.row]

    return cell
}

I have the FirstTableView set as the delegate and datasource, in the editor.

I created a new subclass named: TableViewCell, linked the label to that class. Now I am at at loss as to how to output the movieArray to that label.

Upvotes: 1

Views: 2438

Answers (3)

nitin.agam
nitin.agam

Reputation: 2142

Look out into these points:

  • You have created an outlet of the label named as 'movieTitleLabel' in ViewController, but this label should be in TableCell class. Make correct reference of this label.
  • After the first point, now to access this label, follow this code:

Code:

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "YourTableCellIdentifier", for: indexPath) as! YourTableCellClass
        cell.movieTitleLabel.text = "Text" // Set your text here now
     return cell
 }

Upvotes: 1

Robert Dresler
Robert Dresler

Reputation: 11150

You forgot to downcast cell to your UITableViewCell subclass so you have reference just to superclass UITableVoewCell and this superclass hasn’t any movieTitleLabel.

To fix this, add as! YourTableViewCellSubclass to the end of the line where you dequeue cell

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

Upvotes: 1

Chris Shaw
Chris Shaw

Reputation: 1610

Your prototype cell should have specified an implementation class - this must be a subclass of UITableViewCell. If you've done this, downcast the result of dequeueReusableCell to this class.

You should also have connected the movieTitleLabel outlet in that class to the label in the storyboard. It looks from the above as if you've connected it to the UITableViewController instead (@IBOutlet weak var movieTitleLabel: UILabel!). You should remove this from the VC and only have it in the UITableViewCell class.

Upvotes: 0

Related Questions