Cells aren’t just cells


I was making a table view controller with custom cells. The cells needed to have an image and a new title. There are tutorials of how to subclass the UITableViewCell, but for some reason I didn’t want to go that direction. Then I remember a little app I was playing with where this was accomplished with utilizing the “tag” attribute.

I’ve skipped a few steps (like setting up the table view controller, naming the cell and selecting the prototype cell), and jumped to the juicy part. Add a UIImageView and a UILabel the the the prototype cell. As in the image below, select each and assign a unique tag number.

UITableViewCell-tag

Once that is done, you will need to target the items in the method that creates the cell.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

let cellTitle: UILabel? = cell.contentView.viewWithTag(101) as? UILabel

cellTitle?.text = yourArray[i] as? String

let cellImage: UIImageView? = cell.contentView.viewWithTag(100) as? UIImageView

cellImage?.image = UIImage(named: "image_name.png")

return cell

}

Of course, you will have to assign your values to populate the table view, but this should work if you want to avoid subclassing a table view cell!