I would like to add checkmarks to my Table View cells. I would think to just implement cell.accessoryType = UITableViewCellAccessoryCheckmark
in my didSelectRowAt
method, but I can't get this to work when using a custom UITableViewCell
subclass.
Custom cell:
class TableCell: UITableViewCell {
@IBOutlet weak var tableLabel: UILabel!
var arrayOneToDisplay:ArrayOne?
let arrayOne = ArrayOne()
func displayTable(_ currentArrayOne:ArrayOne) {
// Keep a reference to the cell
arrayOneToDisplay = currentArrayOne
// Get the Table Cells data
var tableCell = arrayOne.tableCells
// Set the instructionLabel
tableLabel.text = currentArrayOne.tableCells![0]
}
ViewController:
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Make sure the array contains at least 1 item
guard arrayOne.count > 0 else {
return 0
}
// Return the number of items for this array
let currentArrayOne = arrayOne[currentArrayOneIndex!]
if currentArrayOne.tableCells != nil {
return currentArrayOne.tableCells!.count
}
else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Get a cell
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
// Get the instruction that the tableView is asking about
let tableLabel = cell.tableLabel
if tableLabel != nil {
let currentArrayOne = arrayOne[currentArrayOneIndex!]
if currentArrayOne.tableCells != nil && indexPath.row < currentArrayOne.tableCells!.count {
// Set the text for the label
tableLabel!.text = currentArrayOne.tableCells![indexPath.row]
}
}
// Return the cell
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
When I try to implement cell.accessoryType
in the ViewController, Xcode doesn't recognize accessoryType
. I believe it's because my methods are for UITableView
and not UITableViewCell
, so the added wrinkle of using a custom cell is causing some confusion for me. Any guidance is much appreciated!
You should set your accessoryType
in the cellForRowAt
method, try to rewrite it as this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
cell.accessoryType = .checkmark
guard let arrayOneIndex = currentArrayOneIndex, arrayOneIndex < arrayOne.count else { return cell }
let currentArrayOne = arrayOne[arrayOneIndex]
guard let tableCells = currentArrayOne.tableCells, indexPath.row < tableCells.count else { return cell }
cell.tableLabel.text = tableCells[indexPath.row]
return cell
}