TableView - Customize it!

Dear Swift Community,


to make it short: I want to create a Table View containing an image and a label in each cell. For the prototype cell I created a prototype class of superclass UITableViewCell.


In my ViewController I have the function


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


How can I include the outlet information from the prototype class into this function of the view controller class?


By entering something like this: cell.mainImageView.image = .... - mainImageView is of course unknown, because it is from the other class.


Lastly: English is not my native language. Hope you will unterstand my issue anyway. Thanks in advance!


Cheers

Accepted Answer

When you dequeue or create your new cell, in tableView(_:cellForRowAt:), you're actually creating an instance of your subclass, so you can cast the created cell to your subclass. That will let you reference the "mainImageView" outlet. Note that you must also connect this outlet to the UIImageView in IB.


So, you'll have code like this:


class MyCell: UITableViewCell {
     @IBOutlet var mainImageView: UIImageView!
     …
}
…
func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
     let cell = dequeueReusableCell (…) as! MyCell
     cell.mainImageView.image = …
}

Thank you! This helped me a lot as a newbie !!


I created the prototype cell -> connected it to a prototype class by an outlet -> referenced it to the viewController file by the dequeuReusableCell command.


Now everything works, BUT there is a small error: The imageView outlet from the View Controller to the UIIMageView is invalid. Outlets cannot be connected to repeating content. Main.storyboard


In another forum I found this answer: Create a table view cell subclass and set it as the class of the prototype. Add the outlets to that class and connect them. Now when you configure the cell you can access the outlets.


Can somebody explain this to me?


Is that the right answer and can somebody explain this to a newbie. It would help me a lot to save some of the remaining hair of my sculp.


Thanks a lot !!!!!!!!!!!!!!!

>Outlets cannot be connected to repeating content.


Did you confirm to delete old connections? Check Interface Builder to confirm.


Did you perform a 'clean build folder' (hold down on the option key, then use the Product menu and choose to 'clean build folder') before building and testing again?

TableView - Customize it!
 
 
Q