Dmitriy Vinnichuk Dmitriy Vinnichuk - 16 days ago 5
Swift Question

Custom TableViewCell | Swift

I'm trying to add to table different content such as images/text.
I've created 2 custom tableViewCells for both types. I have the main array, where it all will be saved (images encode to base64 because of storing in JSON).

var content = [String]()
var imgCell: ImageTableViewCell = ImageTableViewCell()
var txtCell: TextTableViewCell = TextTableViewCell()


Having two buttons for adding images/text.

@IBAction func textAddButton(sender: AnyObject) {
self.content.append("text")
self.articleTableView.reloadData()
}


In updating the table i cant understand how to connect array data with custom cells and display it.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
if content[indexPath.row] == "text" {
return txtCell
}
else {
return imgCell
}
return UITableViewCell()
}


Here is custom cell.

class TextTableViewCell: UITableViewCell {

@IBOutlet weak var textArticle: UITextView!

}

Answer

You never initialize cells like that. Inside cellForRowAtIndexPath you call dequeueReusableCellWithIdentifier and depending on the indexPath you setup the cell accordingly. If you've created the cells in a Storyboard file make sure to set their identifiers in the storyboard.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell = tableView. dequeueReusableCellWithIdentifier(identifierForIndexPath(indexPath), forIndexPath:indexPath)
    // set up cell accordingly
}

func identifierForIndexPath(indexPath:NSIndexPath) -> String {
    // for example: (you can set this up according to your needs)
    if (indexPath.row == 0) {
        return "ImageCell" // these must match your identifiers in your storyboard
    }
    return "TextCell"
}

Alternatively you can have separate blocks in cellForRowAtIndexPath for each cell type, and then you would have something like:

let cell = tableView.dequeueReusableCellWithIdentifier("TextCell", forIndexPath:indexPath) as! TextTableViewCell
Comments