iOS Tutorials: Making radio buttons

Kelvin Tan
4 min readAug 8, 2019

Originally published on: https://daddycoding.com/2019/08/07/ios-tutorials-making-radio-buttons/

OVERVIEW

Radio button become one of the choices if the app requires additional informations from the user as it retrieves choice picked by user. It is also one of a way to know the user preference. Isn’t it considered user friendly if the user is able to pick their own choice?

Let’s dive into making a radio button work for the apps.

BUILDING THE UITABLEVIEWCELL

First, create a custom UITableViewCell by New > File > Cocoa Touch Class

Make sure that the subclass is of type UITableViewCell and Also create XIB file is checked.

It should look pretty straight forward with an image and a button on the UITableViewCell.

When all the above is done. It’s time to write a little code that will handle the text and the selection. This is how the code will look like.

import UIKitclass RadioButtonTableViewCell: UITableViewCell {	// 1
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var iconImage: UIImageView!
// 2
private let checked = UIImage(named: "checked-radio")
private let unchecked = UIImage(named: "unchecked-radio")
// 3
override func awakeFromNib() {
super.awakeFromNib()
}
// 4
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
// 5
public func configure(_ text: String) {
titleLabel.text = text
}
// 6
public func isSelected(_ selected: Bool) {
setSelected(selected, animated: false)
let image = selected ? checked : unchecked
iconImage.image = image
}
}
  1. This is where you will create an IBOutlet for your object
  2. This is the image variable, you may download the asset from Icons8
  3. This is the default function or in a more familiar way, it does the same thing as viewDidLoad
  4. This is also a default function created which handles the selection
  5. This is being used later to create a title for each cell
  6. This is where it is being determined if the cell is selected. And if it is…

--

--

Kelvin Tan

Father, husband, software engineer. Building software and building a family, one line of code and one moment at a time. 🚀💻💙 http://ko-fi.com/kelvintanzy