Radio button effect in Swift

What is the best way to achieve a radio button effect?


So far, I have used addTarget to detect the touch:


button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)


func buttonPressed(_: AnyObject){
        self.layer.backgroundColor = UIColor.green().cgColor
    }


This however, only works as a checkbox, not the radio button.


Any help is much appreciated!

Have you tried a segmented control (UISegmentedControl)? It works well if each label is short, but doesn't work as well when the text you want on each label is long.

This works for OS X (sorry, Mac OS).


If you connect different buttons to the same IBAction, it is automatically handled as radio buttons.


I don't remember if this works for IOS.

Thanks for sharing your thoughts! Just a little bit of context to what I am trying to achieve...

It’s going to be an iOS app with ~50 buttons of the same style and behaviour. Think of the calendar view where one can select only one day. Active selection changes the button appearance. It seemed that reusable sub-class is a better approach vs IBActions...


Probably, UIButton subclass isn’t the best way forward, given that these buttons would be presented within a grid in 7 columns.


I did find some samples for radio buttons, but would like to learn the rationale behind the creation instead of just reusing..


Any thoughts whether UITableView could do the job?

You probably want a single custom view. Note that in many cases, UI that offers a grid of "cells" allows users to tap (initially select the touched cell), then move around to select different cells.

If you want a grid, a UICollectionView would be a better fit than a UITableView.

Are there any predefinied methods to achieve a radio button effect using UICollectionView?

Accepted Answer

No, you would have to manage the appearance of the appropriate cell(s) yourself when the delegate methods are called in response to user actions.

Radio button effect in Swift
 
 
Q