Ask Your Question
2

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

asked 2023-01-09 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-12-05 04:00:00 +0000

djk gravatar image

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.
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-09 11:00:00 +0000

Seen: 14 times

Last updated: Dec 05 '21