Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is the process to add a radio button with a check mark on a TableView cell using Swift:

  1. Create a custom TableView cell class that includes a radio button and a label to display the cell's text.
class RadioTableViewCell: UITableViewCell {

    @IBOutlet weak var radioButton: UIButton!

    @IBOutlet weak var label: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        // Setup the radio button
        radioButton.setImage(UIImage(named: "unchecked"), for: .normal)
        radioButton.setImage(UIImage(named: "checked"), for: .selected)
    }

}
  1. In your TableView delegate methods, set the custom cell class for the cell you want to display the radio button on.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "RadioCell", for: indexPath) as! RadioTableViewCell

    // Set the label text for the cell
    cell.label.text = "Option \(indexPath.row + 1)"

    return cell
}
  1. In the didSelectRowAt delegate method, toggle the selected state of the radio button and deselect the cell.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! RadioTableViewCell

    // Toggle the radio button's selected state
    cell.radioButton.isSelected = !cell.radioButton.isSelected

    // Deselect the cell
    tableView.deselectRow(at: indexPath, animated: true)
}
  1. Handle the user's selection in your code as needed, using the isSelected property of the radio button to determine which option was chosen.