Using Radio buttons in iOS application Swift - SKRadioButton


Installation

CocoaPods

You can use CocoaPods to install SKRadioButton by adding it to your Podfile:

platform :ios, '9.0'
use_frameworks!
pod 'SKRadioButton'

To get the full benefits import SKRadioButton wherever you import UIKit

import UIKit
import SKRadioButton

Manually

  1. Download and drop SKRadioButton.swift in your project.
  2. Congratulations!

Usage example

Step 1: Open Storyboard, Drag and drop a UIButton inside your view of ViewController.

Drag & Drop Button

Step 2: Change the Class and Module from Class inspector for UIbuttons which you want to convert to Radio button.

Change Class

Step 3: Select your buttons, Change Type to Custom, remove button Title + Image + Background. Apply Radio buttons customization.

Change Attributes

Change Attributes2

Step 4: Place your Radio buttons inside a stack view (recommended) & apply necessary constraints as per your needs.

Use Stackview

Step 5: One by one, select your Radio buttons & connect with Outlet Collection to your viewController as indicated below.

Outlet Collection

Step 6: One by one, select your Radio buttons & connect same Action to your viewControllers IBAction as indicated below.

IBAction Connection

Step 7: Add following piece of code & you’re done.

import UIKit
import SKRadioButton // Step 1. Import SKRadioButton

class ViewController: UIViewController {

  // Step 2. collection of radio buttons
  @IBOutlet var genderRadioButtons: [SKRadioButton]!

  override func viewDidLoad() {
    super.viewDidLoad()
  }

  // Step 3. On tap update 'isSelected' attributes
  @IBAction func genderRadioButtonsTapped(_ sender: SKRadioButton) {
    genderRadioButtons.forEach { (button) in
      button.isSelected = false
    }
    sender.isSelected = true
  }

 }

Cheers.