Deselect button (Radio Button) Swift 3 iOS - ios

I am trying to make 2 buttons in Swift behave like Radio Buttons.
Each button has a different image for when they are Selected and Not Selected.
When I click one button, I want the other Button to go back to being in the "Not Selected" state and showing the "Not Selected" image if it was previously selected.
I'm using a switch statement:
func toggle(sender: UIButton) {
switch sender.tag {
case 1:
sender.isSelected = !sender.isSelected
case 2:
sender.isSelected = !sender.isSelected
default:
sender.isSelected = !sender.isSelected
}
}
This statement works for changing the buttons, but allows for both to be selected at the same time. How do I make it so that the other button is de-selected when you click the other one of the buttons?

You probably want to create outlets for you buttons then every time the toggle func is fired set both to unselected and then set the sender selected.
func toggle(sender: UIButton) {
//Sender is already selected no need to do anything
if sender.isSelected {
return
}
button1.isSelected = false
button2.isSelected = false
sender.isSelected = true
}

Related

How to toggle background between two buttons in Swift?

I created an app with two buttons. What I want is when the left button is clicked, it will change it's background color. If the right button is clicked, change that background color.
Above concept is working with the following code for both buttons:
#IBAction func pressedButton(_ sender: UIButton) {
sender.backgroundColor = (sender.backgroundColor == Constants.BOOL_BUTTON.enabled) ? Constants.BOOL_BUTTON.disabled : Constants.BOOL_BUTTON.enabled
}
Both buttons are linked to this function. The only thing what is not working, is that when the left button for example had the enabled color and the user then clicks on the right button to change his choice, the left button will not be resetting to it's disabled color. How can I achieve this with above function?
The problem with your code is when right or left button is pressed, it doesn't know about the state of the other one. What you can do is:
#IBAction func pressedButton(_ sender: UIButton) {
if sender.backgroundColor == Constants.BOOL_BUTTON.enabled {
return
}
sender.backgroundColor = Constants.BOOL_BUTTON.enabled
switch sender {
case self.leftButton:
self.rightButton.backgroundColor = Constants.BOOL_BUTTON.disabled
case self.rightButton:
self.leftButton.backgroundColor = Constants.BOOL_BUTTON.disabled
default:
return
}
}

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

I have two UIButtons that I want to use to set an A/B value to a variable before I save data to a database. I want a button to become selected when tapped, and deselected when the other button is tapped, and vice versa. What is a good solution for accomplishing this programmatically or in Interface Builder?
In order to set an "A/B value" as you mention, the easiest option would be to use a UISwitch or -in the general case of possibly more than 2 options- a UISegmentedControl (as #rmaddy suggested in the question's comments) .
These controls have built-in the "choose just one out of many" functionality that you are looking for.
The drawbacks of the switch are:
It has to be either on or off (does not support a selection state of "neither A nor B")
You can't have separate title labels for each state.
If you still want two separate UIButton instances, you can:
Have references to both buttons in your view controller (#IBOutlets wired using Interface Builder), e.g.:
#IBOutlet weak var leftButton: UIButton!
#IBOutlet weak var rightButton: UIButton!
Implement the action method for both buttons in such a way that it sets the selected state of the tapped button, and resets the other one. For example:
#IBAction func buttonAction(sender: UIButton) {
if sender == leftButton {
leftButton.isSelected = true
rightButton.isSelected = false
} else if sender == rightButton{
leftButton.isSelected = false
rightButton.isSelected = true
}
}
This is a quick-and-dirty solution for just two buttons. If you want a generic radio group of n-buttons, there are open source solutions on GitHub, etc...
Try this.
First create both button separate #IBOutlet.
#IBOutlet weak var btnYes: UIButton!
#IBOutlet weak var btnNo: UIButton!
Set Both Button Tag Like this and you also set tag using storyboard.
override func viewDidLoad() {
super.viewDidLoad()
btnYes.tag = 1
btnNo.tag = 2
}
Implement Common #IBAction method for both buttons
#IBAction func btnYesNoTapped(_ sender: UIButton) {
if sender.tag == 1 {
self.IsBtnSelected(isSelect: true, with: self.btnYes)
}else {
self.IsBtnSelected(isSelect: true, with: self.btnNo)
}
}
Create Custome Method
func IsBtnSelected(isSelect:Bool,with sender:UIButton){
self.btnYes.isSelected = false
self.btnNo.isSelected = false
sender.isSelected = isSelect
}
you can use following function for creating a radio button behaviour, you have to btn outlet to be selected and array of both outlets to this function. instead ofcolor you can also compare images and set images. for getting a required value yo can create a variable in viewcontroller and assign this variable a value in IBAction of btn and you can call this function from IBAction.
func radioButton(_ btnToBeSelected: UIButton, _ btnArray: [UIButton]) {
for btn in btnArray {
if btn == btnToBeSelected {
btn.backgroundColor = UIColor.black
//selected btn
//You can also set btn images by
//btn.setImage(<#T##image: UIImage?##UIImage?#>, for: <#T##UIControlState#>)
} else {
btn.backgroundColor = UIColor.red
//not selected btn
}
}
}
In iOS , you would have to do it manually.See the below approaches,
Use a switch . Using a UISwitch would be better if the option indicates a on/off state.
Use a same method when the button is pressed. Whenever the method gets called deselect the other button/buttons and select the pressed button. You can use tags or keep a reference of the buttons to differentiate between them.
Lastly , keep different methods for each buttons . Just deselect the other buttons whenever the button is pressed.
You can follow the above approaches by using interface builder or programmatically.
You can achieve it like below
I have implemented it for dates which are in TableView you just need to do little modifications
enum filterDateSelectableOptions:Int {
case AssignDate
case DueDate
case CompletionDate
}
//Assign Date selected by default
var currentSelectedFilterDate:filterDateSelectableOptions = .AssignDate
Now
func btnRadioButtonTapped(sender:UIButton) {
switch sender.tag {
case kTableViewRow.AssignDate.rawValue:
self.currentSelectedFilterDate = .AssignDate
case kTableViewRow.DueDate.rawValue:
self.currentSelectedFilterDate = .DueDate
case kTableViewRow.CompletionDate.rawValue :
self.currentSelectedFilterDate = .CompletionDate
default:
break;
}
//sender.isSelected = !sender.isSelected
self.tblFilterList.reloadData()
}
in cellForRow I have
// THIS IS DIFFERENT ENUM SO +1 is required in my case
case .AssignDate,.DueDate,.CompletionDate :
let button = buttonRadioCircle
button.tag = row.rawValue
cell.accessoryView = button
button.addTarget(self, action: #selector(btnRadioButtonTapped(sender:)), for: .touchUpInside)
button.isSelected = self.currentSelectedFilterDate.rawValue + 1 == row.rawValue
}

Simple way to set Button Active Color in iOS Swift

Ive been looking around for methods to change active state on Button click. I have 4 buttons when clicked the reposition my scroll view as programmed.
I am trying to set the background color to fade a bit if clicked. Im able to set the background color but it stays the same faded color when another is clicked. It doesnt return to an inactive state.
Any simple way to acheive this onckick button behavior globally?
heres my button click func's:
#IBAction func tab1(sender: UIButton)
{
slScrollView.setContentOffset(CGPointMake(0.0, 0.0), animated: true)
tab1.backgroundColor = UIColor.grayColor()
tab2.selected = false
tab3.selected = false
}
#IBAction func tab2(sender: UIButton)
{
slScrollView.setContentOffset(CGPointMake(0.0, 650.0), animated: true)
tab2.backgroundColor = UIColor.grayColor()
tab1.selected = false
tab3.selected = false
}
#IBAction func tab3(sender: UIButton) {
slScrollView.setContentOffset(CGPointMake(0.0, 1370.0), animated: true)
tab3.backgroundColor = UIColor.grayColor()
tab1.selected = false
tab2.selected = false
}
First, create an IBOutletCollection (or four separate outlets) to the buttons. Then create an IBAction method and set all four buttons to fire it when tapped. In the method, do the background fade animation on the button that fired the action (which is passed into the handler as its sender argument, then reset the states of the other outlet buttons.
The way I would code it:
// Outlet to all of the buttons. ctrl+drag each button to this outlet.
#IBOutletCollection buttons = [UIButton]()
// Set *all* of the buttons to fire this method.
#IBAction func buttonTapped(sender: AnyObject!) {
(sender as? UIButton).backgroundColor = <whatever>
for button in buttons.filter({ $0 != sender }) {
button.backgroundColor = <default>
}
}

One UIbutton can be chosen at a time

I have three buttons,and only one button can be chosen by the user at a time,that means that other then the initial state where none are chosen only one button can be at a highlighted state at a time.After another button (a forth one) is clicked,all the previous button's abilities to be clicked on are disabled.How do I do this?
button.enabled = false /// this will make a button disabled in swift
Why not use the 4th button to toggle a bool - that can be used to check on the state of the other buttons?
var lockedButtons: Bool = true
#IBAction func toggleButtonLock(sender: UIButton) {
lockedButtons = !lockedButtons
}
#IBAction func Button1(sender: UIButton) {
if !lockedButtons{
//Button1 code
}
}
//button 2 & 3 code similar....

Swift - Change color and size of text when UIButton is tapped

Basically, I have a three buttons on my main screen.
When I select one of these buttons, I would like the text on the selected button to change to bold and change color (blue).
When I select a different button, I would like the newly selected button to change to bold and change color(blue), and the previously selected button to go back to normal. (non-bold and black text)
I have these buttons sending an action to the script.
This is what I have, I can't seem to get it to work. Help would be much appreciated!
#IBAction func buttonOne(sender: UIButton){
sender.setTitleColor(UIColor.blueColor(), forState: UIControlState.Highlighted)
}
I have tried .Highlighted and .Selected on the UIControlState, neither seem to work. I have also tried the following, but I cant get it to work.
#IBAction func buttonOne(sender: UIButton){
sender.titleLabel?.textColor = UIColor.blueColor()
}
I figured that since the sender was a UIButton, and it was the button that was clicked, taking the values off of it and resetting them would work. I do believe I am missing something.
Thank you
Sounds like you want UIControlState.Normal
Selected does nothing in most cases, and Highlighted is only while you're pressing the button.
See more info here: https://developer.apple.com/library/ios/documentation/uikit/reference/uicontrol_class/index.html#//apple_ref/doc/constant_group/Control_State
Maybe you can do with a transform...
#IBAction func buttonPressed(sender: UIButton) {
sender.titleLabel!.textColor = UIColor.blueColor()
sender.transform = CGAffineTransformMakeScale(0.8, 0.8)
}
#IBAction func buttonReleased(sender: UIButton) {
sender.titleLabel!.textColor = UIColor.redColor()
sender.transform = CGAffineTransformIdentity
}
Provide tags to all buttons, connect each button actions to same function and try the following code:
#IBAction func butnClicked (sender : UIButton) {
for tg in 1...2 {
print(sender.tag)
let tmpButton = self.view.viewWithTag(tg) as? UIButton
if tmpButton?.tag == sender.tag {
tmpButton?.setTitleColor(.red, for: .normal)
} else {
tmpButton?.setTitleColor(.gray, for: .normal)
}
}
Hope will be helping.

Resources