how to create single selection check box in swift2? - ios

import UIKit
class CheckBox: UIButton {
// Images
let checkedImage = UIImage(named: "check-sign.png")! as UIImage
let uncheckedImage = UIImage(named: "blank-square.png")! as UIImage
// Bool property
var isChecked: Bool = false {
didSet{
if isChecked == true {
self.setImage(checkedImage, forState: .Normal)
} else {
self.setImage(uncheckedImage, forState: .Normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
}
}
}
I was trying to implement checkboxes in Swift 2. I was referring to How to create radio buttons and checkbox in swift (iOS)?.
But my requirement is I want to implement single selection checkbox. I am not sure how to group the buttons via IB to make it single selectable.
Any suggestion?
Currently it is multiple selectable, I want to make it single selectable.

You can do it with UITableView and custom cells ,and change tableView.allowsMultipleSelection = flase.
Ex : You can do that by setting the accessoryType on the selected UITableViewCell instances to UITableViewCelAccessoryCheckmark.
To deselect the row, set it back to UITableViewCellAccessoryNone.

Related

Swift create custom logic for radio button

I have four custom UIButton, I applied button image radio (checked and checked). four button I have separate action method I can change the Image easily but if I checked first button another three button need uncheck. it should react like radio button.
Here, below my code
#IBAction func first_scheme(_ sender: Any) {
bRec = !bRec
if (bRec == true) {
firstscheme_button.setImage(UIImage(named: "uncheck.png"), for: .normal)
} else {
firstscheme_button.setImage(UIImage(named: "check.png"), for: .normal)
}
}
If you have 4 radio buttons at all times, you can put them in an array.
var radioButtons: [ButtonType] = [r1, r2, r3, r4]
You can now access the button in a loop and set the values for the other button to 'unchecked'.
func setRadioButtons(button: ButtonType) {
for radioButton in radioButtons {
if radioButton !== button {
radioButton.setImage(UIImage(named: "uncheck.png"), for: .normal)
}
}
}
#IBAction func first_scheme(_ sender: Any) {
bRec = !bRec
if bRec {
firstscheme_button.setImage(UIImage(named: "uncheck.png"), for: .normal)
} else {
firstscheme_button.setImage(UIImage(named: "check.png"), for: .normal)
}
setRadioButtons(button: sender)
}
alternate method
If all you want to do is check the button clicked and uncheck the other buttons, the logic is simpler.
Create the common action for all radio buttons as well create the IBOutletcollection for your all UIButtons ,
var radioButtons: [UIButton] = [r1, r2, r3, r4]
finally execute the common method as
func setRadioButtons(button: UIButton) {
for getradioButton in radioButtons {
getradioButton.setImage(UIImage(named: "uncheck.png"), for: .normal)
}
button.setImage(UIImage(named: "check.png"), for: .normal)
}
I suggest you set tags on the buttons with the simple tag property, and then you save it from a generic listener.
//first button selected
var lastTag = 0
#IBAction func first_scheme(_ sender: UIButton) {
buttonArray[lastTag].setImage(UIImage(named: "uncheck.png"), for: .normal)
lastTag = sender.tag
sender.setImage(UIImage(named: "check.png"), for: .normal)
}
You Can override isSelected variable in the custom UIButton and set the image depend on the isSelected value.
class customButton: UIButton {
override var isSelected: Bool {
willSet {
self.setImage(UIImage.init(named: "checked"), for: .normal)
}
didSet {
self.setImage(UIImage.init(named: "unchecked"), for: .normal)
}
}
}
After making 4 IBOutlets and 4 IBActions for the four custom UIButtons. you can easily select and unselect the buttons and apply your custom behaviour.
#IBAction func firstButtonAction(_ sender: Any) {
if let button = sender as? customButton {
button.isSelected = !button.isSelected
}
secondButton.isSelected = false
thirdButton.isSelected = false
fourthButton.isSelected = false
}

Set CheckBox on - off

I made a custom checkbox with button by creatin a class of UIButton
here is the class
import UIKit
class CheckBox: UIButton {
// Images
let checkedImage = UIImage(named: "ic_check_box")! as UIImage
let uncheckedImage = UIImage(named: "ic_check_box_outline_blank")! as UIImage
// Bool property
var isChecked: Bool = false {
didSet{
if isChecked == true {
self.setImage(checkedImage, forState: .Normal)
} else {
self.setImage(uncheckedImage, forState: .Normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
}
}
}
I have two checkboxes in the viewcontroller but I dont know how to set checkbox in the ViewController.class to do when checkBox "Si" is checked, the checkbox "No" set unchecked like in the image
Your CheckBox class should adopt a delegation pattern so that it can advise its delegate (which in this case would be your view controller) that its value has changed. Then in your view controller you can update the other checkbox as required:
protocol CheckBoxDelegate {
func checkBoxDidChange(checkbox: CheckBox) -> Void
}
class CheckBox: UIButton {
// Images
let checkedImage = UIImage(named: "ic_check_box")! as UIImage
let uncheckedImage = UIImage(named: "ic_check_box_outline_blank")! as UIImage
weak var delegate: CheckBoxDelegate?
// Bool property
var isChecked: Bool = false {
didSet{
if isChecked == true {
self.setImage(checkedImage, forState: .Normal)
} else {
self.setImage(uncheckedImage, forState: .Normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonClicked(sender: UIButton) {
isChecked = !isChecked
self.delegate?.checkBoxDidChange(self)
}
}
Then, in your View Controller:
class ViewController: UIViewController, CheckBoxDelegate {
#IBOutlet var siCheckBox: CheckBox! // Initialise some other way if you aren't using storyboard/nib
#IBOutlet var noCheckBox: CheckBox!
override func viewDidLoad() {
super.viewDidLoad()
self.siCheckBox.delegate = self
self.noCheckBox.delegate = self
}
//Mark: CheckBoxDelegate
func checkBoxDidChange(checkbox: CheckBox) {
if checkbox == self.siCheckBox {
self.noCheckBox.isChecked = !checkbox.isChecked
} else {
self.siCheckBox.isChecked = !checkbox.isChecked
}
}
From a user experience point of view, I would question why you need both checkboxes. A checkbox is an on/off control, so you would normally have text like "Select really great option?" with a single checkbox for yes/no; checked is yes, unchecked is no.
I would move func buttonClicked(sender: UIButton) to the parent ViewController.
let siCheckBox = CheckBox()
let noCheckBox = CheckBox()
func checkBoxToggled(sender: AnyObject) {
noCheckbox.isChecked = !noCheckbox.isChecked
siCheckbox.isChecked = !siCheckbox.isChecked
}
This is only safe if you're sure at least 1 is always checked. Otherwise I would add an if statement to make sure at l is checked.

Removed Selected State on Button While Clicking a Different Button (Swift)

I'm trying to figure out the logic in toggling button states in Swift. The concept is very simple:
I have three buttons on the screen.
When I click one button, it toggles to a 'selected' state
When I click a different button, I want it to toggle the currently selected button to a 'non-selected' state and toggle the new button to 'selected'
I have this function I use on TouchUpInside for the buttons on the screen but at the moment it's possible to have them all 'selected' which I don't want:
func highlightTrack(sender:UIButton){
if(!sender.selected){
sender.selected = true
sender.backgroundColor = UIColor.blueColor()
} else {
sender.selected = false
}
}
I come from the world of Javascript so I may just have my logic crossed up but is there a way to detect currently selected buttons on the screen and turn them off or is this closer to a 'radio' button type logic?
My issue is that these buttons are created programmatically depending on certain conditions so technically I'm not supposed to be created IBOutlets on the fly like that correct (IB meaning 'Interface Builder'?)?
Thanks for your help!
func highlightTrack(sender:UIButton) {
if sender.isSelected {
return
}
btn1.isSelected = false
btn2.isSelected = false
sender.isSelected = true
}
Connect following action function with all your three buttons using TouchUpInside control event.
button1.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
button2.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
button3.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
#IBAction func highlightTrack(button: UIButton) {
if button.isSelected {
return
}
button1.isSelected = false
button1.backgroundColor = UIColor.white
button2.isSelected = false
button2.backgroundColor = UIColor.white
button3.isSelected = false
button3.backgroundColor = UIColor.white
button.isSelected = true
button.backgroundColor = UIColor.blue
}
Another solution:
#IBAction func highlightTrack(button: UIButton) {
if button.isSelected {
return
}
updateButtionSelectionState(button: button, isSelected: (button == button1))
updateButtionSelectionState(button: button, isSelected: (button == button2))
updateButtionSelectionState(button: button, isSelected: (button == button3))
}
func updateButtionSelectionState(button: UIButton, isSelected: Bool) {
button.isSelected = isSelected
button.backgroundColor = isSelected ? UIColor.blue : UIColor.white
}

custom checkbox in uicollectionviewcell swift ios

hi i working on food app, the app has foods in collectionviewcell and i added checkbox in cell so how i can select some foods from cell by checkbox ,
i add the checkbox in collection view cell and add class for button but when i click on checkbox in first cell the all other cells is selected,
the checkbox code
var isCheckedGlobal = Bool() // !! Global Variable // You might need to change '= Bool()' to '= false' or '= true'
class CheckBox: UIButton {
//images
let checkedImage = UIImage(named: "checked") as UIImage?
let unCheckedImage = UIImage(named: "unchecked")as UIImage?
//bool propety
var isChecked:Bool = false{
didSet{
if isChecked == true{
self.setImage(checkedImage, forState: .Normal)
}else{
self.setImage(unCheckedImage, forState: .Normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonClicked(sender:UIButton) {
if(sender == self){
if isChecked == true{
isChecked = false
isCheckedGlobal = false // !! Set variable's value
}else{
isChecked = true
isCheckedGlobal = true // !! Set variable's value
}
}
}
}
and in collectionview this code
if let foodcodes = self.menu![indexPath.row]["code"] as? NSString {
if isCheckedGlobal == false {
cell.foodNumber.enabled = false
cell.foodNumber.text = ""
} else {
if cell.foodNumber.tag == cell.checkboxx.tag {
cell.foodNumber.enabled = true
cell.foodNumber.text = "1"
}
}
}
1.First make a global mutable array like arrSelectedCells
2.Now in UICollectionView cellForRow set indexpath.row value as a tag to checkbox button.
3.In buttonClicked action, get the tag value from button and store the tag value in arrSelectedCells and also check if the tag is present in arrSelectedCells if it's present then remove it.So that multiple same value tag are not present in arrSelectedCells.
4.Now,UICollectionView cellForRow , check if indexpath.row value is present in arrSelectedCells if present then enable the check-box otherwise disable the check-box.

Multiple UIButtons only one can be selected - subclass in swift

I have written a subclass that selects and deselects buttons. I have put this subclass on around 5 buttons in a View Controller.
I want to amend the code so that if the user selects one and then selects another the first one gets deselected.
I was thinking of using the .tag on the button to count which buttons has been selected and remove the selection when the next button is pressed.
Here is the code :
thanks
class ChangeColour: UIButton {
var buttontagpressed: Int = 0
var isChecked:Bool = false{
didSet{
if isChecked == true {
self.backgroundColor = UIColor(red:0.27, green:0.29, blue:0.31, alpha:1.0)
self.setTitleColor(UIColor.whiteColor(), forState: .Normal)
buttontagpressed = self.tag
}
else
{
self.backgroundColor = UIColor(red:0.09, green:0.83, blue:0.56, alpha:1.0)
self.setTitleColor(UIColor(red:0.24, green:0.24, blue:0.24, alpha:1.0), forState: .Normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: "buttonselected:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonselected (sender:UIButton) {
buttontagpressed = self.tag
if (sender == self)
{
if isChecked == true
{
isChecked = false
}
else
{
isChecked = true
}
}
}
}
Rather than using tag (which I think is quite an ugly solution) I would be inclined to add a property to your class which keeps a reference of the previously selected button. This solution would be much more elegant - Or you could use UINotificationCenter to broadcast a message to all buttons to initiate the deselect.

Resources