ios - How do I make two UIButtons perform like radio buttons in Swift? -
i have 2 uibutton
s 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 (
@iboutlet
s 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
Post a Comment