ios - How do I make two UIButtons perform like radio buttons in Swift? -


i have 2 uibuttons want use set a/b value variable before save data database. want button become selected when tapped, , deselected when other button tapped, , vice versa. solution accomplishing programmatically or in interface builder?

in order set "a/b value" mention, easiest option use uiswitch or -in general case of possibly more 2 options- uisegmentedcontrol (as @rmaddy suggested in question's comments) .

these controls have built-in "choose 1 out of many" functionality looking for.

the drawbacks of switch are:

  • it has either on or off (does not support selection state of "neither nor b")
  • you can't have separate title labels each state.

if still want 2 separate uibutton instances, can:

  • have refeences both buttons in view controller (@iboutlets wired using interface builder), e.g.:

    @iboutlet weak var leftbutton: uibutton! @iboutlet weak var rightbutton: uibutton! 
  • implement action method both buttons in such way sets selected state of tapped button, , resets other one. example:

    @ibaction func buttonacton(sender: uibutton) {     if sender == leftbutton {         leftbutton.isselected = true         rightbutton.isselected = false     } else if sender == rightbutton{         leftbutton.isselected = false         rightbutton.isselected = true     } } 

this quick-and-dirty solution 2 buttons. if want generic radio group of n-buttons, there open source solutions on github, etc...


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -