Blog

Swift tutorial: Creating a radio button with pure code

Curious how to create a radio button in a mobile application built with Swift, but without using Storyboards? Read this short tutorial.

Creating a radio button with no Storyboards but pure code means that the code can be reused as many times, as you want inside UITableView or UICollectionView.

Radio button in Swift

Creating radio buttons with pure code is a piece of cake. First, we need to create UIView that contains:

  • UIButton,
  • UIImage (for checked and unchecked),
  • UILabel (optional).

UIButton is used only for handling user actions. UIImage (if an app is designed for iOS 13 or newer) can use SFSymbols as image. The label is optional and can contain our radio button's description.

Our code will look as follows.

First step: Container view

First, add a container view that will keep all stuff together.

// Container view:

let radioView = UIView()

addSubview(radioView)

radioView.translatesAutoresizingMaskIntoConstraints = false

radioView.heightAnchor.constraint(equalToConstant: 20).isActive = true

Second step: Radio button

Next, we need a button to handle user actions.


// Button for user actions:

let radioButton = UIButton()

radioView.addSubview(radioButton)

radioButton.translatesAutoresizingMaskIntoConstraints = false

radioButton.topAnchor.constraint(equalTo: radioView.topAnchor).isActive = true

radioButton.bottomAnchor.constraint(equalTo: radioView.bottomAnchor).isActive = true

radioButton.leftAnchor.constraint(equalTo: radioView.leftAnchor).isActive = true

radioButton.rightAnchor.constraint(equalTo: radioView.rightAnchor).isActive = true

radioButton.tag = tag

radioButton.addTarget(self, action: #selector(onRadioButtonTap), for: .touchUpInside)

Third step: "Select" option image

And now, an image with the "select" option is needed. We can either use SF Symbols provided by Apple, or just go for some custom image.


// Radio button image:

let radioImage = UIImageView()

radioView.addSubview(radioImage)

radioImage.translatesAutoresizingMaskIntoConstraints = false

radioImage.centerYAnchor.constraint(equalTo: radioView.centerYAnchor).isActive = true

radioImage.leftAnchor.constraint(equalTo: radioView.leftAnchor).isActive = true

radioImage.heightAnchor.constraint(equalToConstant: 15).isActive = true

radioImage.widthAnchor.constraint(equalToConstant: 15).isActive = true

radioImage.layer.cornerRadius = 7

radioImage.layer.borderWidth = 1

As you can see, our image has 2 states that are dependent on the Bool value.


if selected {

    radioImage.layer.borderColor = UIColor.blue.cgColor

    radioImage.backgroundColor = .blue

    radioImage.image = UIImage(systemName: "smallcircle.fill.circle")

    radioImage.tintColor = .white

} else {

    radioImage.layer.borderColor = UIColor.gray.cgColor

    radioImage.backgroundColor = .clear

    radioImage.image = nil

}

Final step: Description label

At last, we can add a label with description to the button.


// Optional label with description

let radioLabel = UILabel()

radioView.addSubview(radioLabel)

radioLabel.translatesAutoresizingMaskIntoConstraints = false

radioLabel.centerYAnchor.constraint(equalTo: radioView.centerYAnchor).isActive = true

radioLabel.leftAnchor.constraint(equalTo: radioImage.rightAnchor, constant: 5).isActive = true

radioLabel.textColor = Colors().labelColor()

radioLabel.font = Fonts().regular12()

radioLabel.text = title

}

Wrapping up

Of course, we need to add a selected variable that will change upon user action. Also a new function onRadioButtonTap() is needed for pass touches. If we’re adding a radio button inside UITableViewCell or UICollectionViewCell, using the tag option is a good idea.

It will help with more than one radio button in a cell.

/// This article proves that we know quite a bit about building mobile apps. Looking for a trusted mobile development partner? Drop us a line!

Check our latest product - it's based on our experience of managing over 50-people strong company. The tool we're missing as a small company and not an enterprise.

humadroid.io is an employee and performance management software. It's an unique tool allowing everyone to be in the loop - by having up to date info about co-workers, time-off, benefits, assets, helping with one-on-ones, being a go-to place for company-wide announcements.

Check out humadroid.io
Top

Contact us

* Required fields

The controller of your personal data provided via this contact form is Prograils sp. z o.o., with a registered seat at Sczanieckiej 9A/10, 60-215 Poznań. Your personal data will be processed in order to respond to your inquiries and for our marketing purposes (e.g. when you ask us for our post-development, maintenance or ad hoc engagements for your app). You have the rights to: access your personal data, rectify or erase your personal data, restrict the processing of your personal data, data portability and to object to the processing of your personal data. Learn more.

Notice

We do not track you online. We use only session cookies and anonymous identifiers for the purposes specified in the cookie policy. No third-party trackers.

I understand
Elo Mordo!Elo Mordo!