DEV Community

Avelyn Hyunjeong Choi
Avelyn Hyunjeong Choi

Posted on

UITableView: Cell - Accessory Types

Accessory Types

  • checkmark Image description
  • detail button Image description
  • detail disclosure button Image description
  • disclosure indicator Image description

Checkmark Implementation Example

@IBOutlet weak var itemsTableView: UITableView!
var items = [
  ["item":"Item 01", "selected": false],
  ...
  ["item":"Item 50", "selected": false]
]

override func viewDidLoad() {
  super.viewDidLoad()
  itemsTableView.dataSource = self
  itemsTableView.delegate = self
}

func numberOfSections(in tableView: UITableView) -> Int {
  return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return items.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let itemCell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath)

  if let item = items[indexPath.row]["item"] as? String,
     let selected = items[indexPath.row]["selected"] as? Bool {

    itemCell.textLabel?.text = item
    if selected {
      itemCell.accessoryType = .checkmark
    } else {
      itemCell.accessoryType = .none
    }
  }

  return itemCell
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  return "Items"
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  guard let selected = items[indexPath.row]["selected"] as? Bool else {
    return
  }
  items[indexPath.row]["selected"] = !selected
  tableView.reloadRows(at: [indexPath], with: .automatic)
}
Enter fullscreen mode Exit fullscreen mode

checkmark image

Top comments (0)