Are you ever frustrated trying to replicate some things that are easily done in HTML, in your app!

This happens a lot for me because I am also a part time web developer. In one particular case, I wanted to incorporate radio button functionality that didn't take much code and was flexible.

I came up with this class. A button that keeps an array of all of the other buttons in it's group and once selected, will make sure that all other buttons are deselected.

Here is the class:

import UIKit

class DownStateButton : UIButton {

    var myAlternateButton:Array<DownStateButton>?

    var downStateImage:String? = "radiobutton_down.png"{


            if downStateImage != nil {

                self.setImage(UIImage(named: downStateImage!), forState: UIControlState.Selected)

    func unselectAlternateButtons(){

        if myAlternateButton != nil {

            self.selected = true

            for aButton:DownStateButton in myAlternateButton! {

                aButton?.selected = false



    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

        super.touchesBegan(touches, withEvent: event)

    func toggleButton(){

        if self.selected==false{

            self.selected = true
        }else {

            self.selected = false

You implement this in your view controller class like this:

@IBOutlet var myRadioYesButton:DownStateButton?
@IBOutlet var myRadioNoButton:DownStateButton?

...Then inside your viewDidLoad function...

myRadioNoButton?.downStateImage = "radiobutton_down.png"  
myRadioNoButton?.myAlternateButton = [myRadioYesButton!]

myRadioYesButton?.downStateImage = "radiobutton_down.png"  
myRadioYesButton?.myAlternateButton = [myRadioNoButton!]  

In this particular instance, I've only created two buttons, a yes/no answer. However, you can include as many other DownStateButtons as you like in the "myAlternateButton" variable.

This is just a little time-saver - hope you found it useful!

Please feel free to ask me any questions in an email or comments!


To make implementation easier, I allowed the myAlternateButton array to contain optional values. I also added a default value for the 'downStateImage' so you can just set this image once within the class rather than for every button.

To implement this class, just create buttons that are a subclass of 'DownStateButton' and the 'myAlternateButton' property to an array of all of the other radio buttons in the group.